zoukankan      html  css  js  c++  java
  • 使用jedis执行lua脚本

    转:

    redis学习(十五) 使用jedis执行lua脚本(实现一个对IP的限流)

    使用jedis执行lua脚本(实现一个对IP的限流)

    上一篇学习了怎么安装lua,这一篇学习编写一个lua脚本用jedis执行,实现对一个IP的限流

    LUA脚本如下,第一次使用incr对KEY(某个IP作为KEY)加一,如果是第一次访问,使用expire设置一个超时时间,这个超时时间作为Value第一个参数传入,如果现在递增的数目大于输入的第二个Value参数,返回失败标记,否则成功。redis的超时时间到了,这个Key消失,又可以访问啦。

    package redis;
    
    import java.util.Arrays;
    
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    
    
    public class LuaTest {
    
        public static void main(String[] args) {
    
            JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
            Jedis jedis = jedisPool.getResource();
            try {
                 String lua = "local num = redis.call('incr', KEYS[1])
    " +
                            "if tonumber(num) == 1 then
    " +
                            "	redis.call('expire', KEYS[1], ARGV[1])
    " +
                            "	return 1
    " +
                            "elseif tonumber(num) > tonumber(ARGV[2]) then
    " +
                            "	return 0
    " +
                            "else 
    " +
                            "	return 1
    " +
                            "end
    ";
                 /**
                    local num = redis.call('incr', KEYS[1])
                    if tonumber(num) == 1 then
                        redis.call('expire', KEYS[1], ARGV[1])
                        return 1
                    elseif tonumber(num) > tonumber(ARGV[2]) then
                        return 0
                    else 
                        return 1
                    end
                 */
                 
                Object result = jedis.evalsha(jedis.scriptLoad(lua), Arrays.asList("localhost"), Arrays.asList("10", "2"));
                System.out.println(result);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (jedis != null) {
                    try {
                        jedis.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
            
    }
  • 相关阅读:
    window对象的方法
    JS注册事件
    JS总结
    JS 扩展方法prototype
    Codeforces 460D Little Victor and Set(看题解)
    Codeforces 891C Envy
    Codeforces 251C Number Transformation
    Codeforces 490F Treeland Tour 树形dp
    Codeforces 605C Freelancer's Dreams 凸包 (看题解)
    几何模板
  • 原文地址:https://www.cnblogs.com/libin6505/p/10797108.html
Copyright © 2011-2022 走看看