本文主要是介绍redis学习(十六) 使用jedis执行lua脚本(实现一个对IP的限流),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用jedis执行lua脚本(实现一个对IP的限流)
上一篇学习了怎么安装lua,这一篇学习编写一个lua脚本用jedis执行,实现对一个IP的限流
LUA脚本如下,第一次使用incr对KEY(某个IP作为KEY)加一,如果是第一次访问,使用expire设置一个超时时间,这个超时时间作为Value第一个参数传入,如果现在递增的数目大于输入的第二个Value参数,返回失败标记,否则成功。redis的超时时间到了,这个Key消失,又可以访问啦。
local num = redis.call('incr', KEYS[1])
if tonumber(num) == 1 thenredis.call('expire', KEYS[1], ARGV[1])return 1
elseif tonumber(num) > tonumber(ARGV[2]) thenreturn 0
else return 1
end
Jedis调用代码
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代码GitHub地址: 地址
上一篇 安装lua
下一篇 使用shardedJedis
这篇关于redis学习(十六) 使用jedis执行lua脚本(实现一个对IP的限流)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!