使用jedis执行lua脚本

转:

2018年09月15日 20:07:26 码农-文若书生 阅读数:1609

使用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])\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";
             /**
                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();
                }
            }
        }
    }
        
}