复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41package com.inspur.inspurTest.test.redis; import redis.clients.jedis.Jedis; /** * author yulinshan * time 2019/5/23 * 限流器,利用redis的incr函数做计数,expire做计时失效 **/ public class Increase { static String key = "count"; static int limitCount = 30; public static void main(String[] args) throws InterruptedException { Jedis j =new Jedis("127.0.0.1",6379); for(int i = 0 ;i < 100 ;i ++ ) { if (!checkKey(j)){ System.out.println("超过限流阈值"); return; } incrKey(j); } } private static void incrKey(Jedis j){ if (j.ttl(key) < 0 ){ j.incr(key); j.expire(key,60); }else{ j.incr(key); } System.out.println("总计访问次数为:"+j.get(key)); } private static boolean checkKey(Jedis j) { if (null != j.get(key)) { if (Integer.parseInt(j.get(key)) >= limitCount) { return false; } } return true; } }
以上的代码借鉴了《架构修炼之道》第90页代码。以上逻辑可以放在网关项目中,对某些请求做限流。用到了包
复制代码
1compile group: 'redis.clients', name: 'jedis', version: '2.9.0'
最后
以上就是自觉心锁最近收集整理的关于利用redis做限流器的全部内容,更多相关利用redis做限流器内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复