带你了解什么是限流 (2)

可以使用Redis+Lua的方式来实现,大致的lua脚本代码如下:

local key = "rate.limit:" .. KEYS[1] --限流KEY local limit = tonumber(ARGV[1]) --限流大小 local current = tonumber(redis.call('get', key) or "0") if current + 1 > limit then --如果超出限流大小 return 0 else --请求数+1,并设置1秒过期 redis.call("INCRBY", key,"1") redis.call("expire", key,"1") return current + 1 end

Java代码如下:

public static boolean accquire() throws IOException, URISyntaxException { Jedis jedis = new Jedis("127.0.0.1"); File luaFile = new File(RedisLimitRateWithLUA.class.getResource("http://www.likecs.com/").toURI().getPath() + "limit.lua"); String luaScript = FileUtils.readFileToString(luaFile); String key = "ip:" + System.currentTimeMillis()/1000; // 当前秒 String limit = "5"; // 最大限制 List<String> keys = new ArrayList<String>(); keys.add(key); List<String> args = new ArrayList<String>(); args.add(limit); Long result = (Long)(jedis.eval(luaScript, keys, args)); // 执行lua脚本,传入参数 return result == 1; }

解释:

Java代码传入key和最大的限制limit参数进lua脚本

执行lua脚本(lua脚本判断当前key是否超过了最大限制limit)

如果超过,则返回0(限流)

如果没超过,返回1(程序继续执行)

参考来源:

https://segmentfault.com/a/1190000016552464

更多资料参考:

https://segmentfault.com/a/1190000016042927

[%E8%87%AA%E5%B7%B1%E5%86%99%E5%88%86%E5%B8%83%E5%BC%8F%E9%99%90%E6%B5%81%E7%BB%84%E4%BB%B6-%E5%9F%BA%E4%BA%8ERedis%E7%9A%84RateLimter/](自己写分布式限流组件-基于Redis的RateLimter/)

最后

乐于输出干货的Java技术公众号:Java3y。公众号内有200多篇原创技术文章、海量视频资源、精美脑图,关注即可获取!

转发到朋友圈是对我最大的支持!

觉得我的文章写得不错,点

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zysdps.html