redis 实现限流的三种方案

互联网产品接口离不开限流:尤其是高并发接口,今天我们分享一下,基于springboot 分享三种方案

一、基于redis 自增原理简单实现

 @Autowired
    StringRedisTemplate stringRedisTemplate;

     /**
     * 接口限流策略
     *
     */
    @Override
    public boolean limitKey(HttpServletRequest request) throws UnknownHostException {

        InetAddress address = InetAddress.getLocalHost();
        String checkedToken = request.getHeader("ND-TOKEN");
        Long uid = getUserid(checkedToken);
        String hostAddress = address.getHostAddress();
        String key = THROTTLE_KEY + hostAddress + "_" + uid + "_";
        log.debug("validation start key:" + key);
        String minKey = key + "min";
        long minTimes = stringRedisTemplate.opsForValue().increment(minKey, 1);
        if (minTimes <= 1) {
            stringRedisTemplate.expire(minKey, 1, TimeUnit.MINUTES);
        }
        String hourKey = key + "hour";
        long hourTimes = stringRedisTemplate.opsForValue().increment(hourKey, 1);
        if (hourTimes <= 1) {
            stringRedisTemplate.expire(hourKey, 1, TimeUnit.HOURS);
        }

        String dayKey = key + "day";
        long dayTimes = stringRedisTemplate.opsForValue().increment(dayKey, 1);
        if (dayTimes <= 1) {
            stringRedisTemplate.expire(dayKey, 1, TimeUnit.DAYS);
        }

        if (minTimes > 10) {
            throw new UnknownHostException();
        }
        if (hourTimes > 20) {
            throw new UnknownHostException();
        }
        if (dayTimes > 50) {
            throw new UnknownHo
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寅灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值