Redis learning (fifteen) use jedis to execute lua script (implement a limit on IP)

Use jedis to execute lua script (implement a limit on IP)

上一篇 Learn how to install lua This one is to write a lua script to execute with jedis, to achieve a limit on an IP

LUA script as follows, the first use of incr to KEY (some IP as KEY) plus one, if it is the first time Access, use expire to set a timeout, this timeout is passed as the first parameter of Value, if the number of increments now is greater than the second Value parameter of the input, the failure flag is returned, otherwise it succeeds. The timeout for redis is up, the Key disappears and you can access it.

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

Jedis Call code

public class Limiter {
    public static void main(String[] args) {
        JedisPool jedisPool = JedisPoolUtils.getInstance();
        Jedis jedis = jedisPool.getResource();
        try {
            String lua = "local num = redis.call('incr', KEYS[1])\n" +
                    "if tonumber(num) == 1 then\n" +
                    "\tredis.call('expire', KEYS[1], ARGV[1])\n" +
                    "\treturn 1\n" +
                    "elseif tonumber(num) > tonumber(ARGV[2]) then\n" +
                    "\treturn 0\n" +
                    "else \n" +
                    "\treturn 1\n" +
                    "end\n";
            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();
                }
            }
        }
    }
}

Java Code GitHub Address: Address