- 添加maven依赖 , 使用springboot2.x版本
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.Apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
- 添加redis配置进Application.yml , springboot2.x版本的redis是使用lettuce配置的
spring: redis: database: 0 host: localhost port: 6379 lettuce: # 这里标明使用lettuce配置 pool: max-active: 8 # 连接池最大连接数 max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制 max-idle: 5 # 连接池中的最大空闲连接 min-idle: 0 # 连接池中的最小空闲连接 timeout: 10000ms # 连接超时时间
- 使用redis作限流器有两种写法
- 方法一:
Long size = redisTemplate.opsForList().size("apiRequest"); if (size < 1000) { redisTemplate.opsForList().leftPush("apiRequest", System.currentTimeMillis()); } else { Long start = (Long) redisTemplate.opsForList().index("apiRequest", -1); if ((System.currentTimeMillis() - start) < 60000) { throw new RuntimeException("超过限流阈值"); } else { redisTemplate.opsForList().leftPush("apiRequest", System.currentTimeMillis()); redisTemplate.opsForList().trim("apiRequest", -1, -1); } }核心思路:用一个list来存放一串值 , 每次请求都把当前时间放进 , 如果列表长度为1000 , 那么调用就是1000次 。如果第1000次调用时的当前时间和最初的时间差小于60s , 那么就是1分钟里调用超1000次 。否则 , 就清空列表之前的值
方法二:
Integer count = (Integer) redisTemplate.opsForValue().get("apiKey"); Integer integer = Optional.ofNullable(count).orElse(0); if (integer > 1000) { throw new RuntimeException("超过限流阈值"); } if (redisTemplate.getExpire("apiKey", TimeUnit.SECONDS).longValue() < 0) { redisTemplate.multi(); redisTemplate.opsForValue().increment("apiKey", 1); redisTemplate.expire("apiKey", 60, TimeUnit.SECONDS); redisTemplate.exec(); } else { redisTemplate.opsForValue().increment("apiKey", 1); }核心思路:设置key , 过期时间为1分钟 , 其值是api这分钟内调用次数
对比:方法一耗内存 , 限流准确 。方法二结果有部分误差 , 只限制key存在的这一分钟内调用次数低于1000次 , 不代表任意时间段的一分钟调用次数低于1000
【redis实现网关限流】
推荐阅读
-
-
-
-
-
国际足球秘闻■仍无法报到,中超版人在囧途!泰达外援3天辗转4国飞回中国
-
巴西|第二个死亡超过10万的国家诞生,总统现在后悔了么?
-
-
游戏日报|荒野乱斗双人生存斯派克太OP?强势骚扰硬核控场,队友只用躺
-
艺术家领军人物 胡国松|光辉历程?新时代| a2857
-
自贡恐龙博物馆|20名四川自贡事实孤儿走进恐龙博物馆当“科考小侦探”
-
中超|中超疯狂的13分钟:3个进球+2次神助攻!升班马被打懵了
-
-
-
-
数码伟视角 1元门槛享5G,压力下的5G重大突破!民营虚商巨头响起价格战
-
-
|想要在工作中获得进步与成长,都需要时刻注意自己的言行举止
-
嘻哈段子|能不能要点脸?,十条笑话:老妹你太自信了
-
低调小刘说体育|马蕴雯嫁给年薪超千万洋帅,他曾与姚迪传过绯闻,惠若琪说媒
-
学了风景园林,打算转行做淘宝美工,可是又被人嫌弃做淘宝美工没前途,真的不知道该干啥