基于redis+lua实现的分布式限流

public class Console {

public static void main(String[] args) {
    Config config = new Config();
    config.setLockWatchdogTimeout(10000);
    config.useSingleServer().setAddress("redis://127.0.0.1:6379");
    RedissonClient redissonClient = Redisson.create(config);

    List<Object> keys = new ArrayList<>();
    keys.add("txk");
    Object[] values=new Object[]{1};
    Object eval = redissonClient.getScript().eval(READ_WRITE, RedisLua.LIMIT_LUA_STRING, RScript.ReturnType.INTEGER, keys, values);
    System.out.println(eval);

}


static class RedisLua {

    public static final String LIMIT_LUA_STRING;

    static {
        StringBuilder limitLuaString =new StringBuilder();
        limitLuaString.append(" local key = KEYS[1]");
        limitLuaString.append("\nlocal limit = tonumber(ARGV[1])");
        limitLuaString.append("\nlocal curentLimit = tonumber(redis.call('get', key) or \"0\")");
        limitLuaString.append("\nif curentLimit + 1 > limit then");
        limitLuaString.append("\nreturn 0");
        limitLuaString.append("\nelse");
        limitLuaString.append("\n redis.call(\"INCRBY\", key, 1)");
        limitLuaString.append("\nredis.call(\"EXPIRE\", key, ARGV[2])");
        limitLuaString.append("\nreturn curentLimit + 1");
        limitLuaString.append("\nend");
        LIMIT_LUA_STRING=limitLuaString.toString();
    }
}

}

posted @ 2020-12-28 14:17  Me无情  阅读(240)  评论(0编辑  收藏  举报