redis zset滑动窗口限流

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

redis zset滑动窗口限流

子非鱼yy   2022-05-23 我要评论

限流

需求背景:同一用户1分钟内登录失败次数超过3次,页面添加验证码登录验证,也即是限流的思想。

常见的限流算法:固定窗口计数器;滑动窗口计数器;漏桶;令牌桶。本篇选择的滑动窗口计数器

redis zset特性

Redis 有序集合(sorted set)和集合(set)一样也是 string 类型元素的集合,且不允许重复的成员。不同的是每个元素都会关联一个 double 类型的分数(score)。redis 正是通过分数来为集合中的成员进行从小到大的排序。

可参考java的LinkedHashMap和HashMap,都是通过多维护变量使无序的集合变成有序的。区别是LinkedHashMap内部是多维护了2个成员变量Entry<K,V> before, after用于双向链表的连接,redis zset是多维护了一个score变量完成顺序的排列。

有序集合的成员是唯一的,但分数(score)可以重复。

滑动窗口算法

滑动窗口算法思想就是记录一个滑动的时间窗口内的操作次数,操作次数超过阈值则进行限流。

网上找的图:

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

java代码实现

key使用用户的登录名,value数据类型使用zset,zset的score使用当前登录时间戳,value也使用当前登录时间戳。

key虽然我用的登录名(已满足我的需求),但建议实际应用时使用uid等具有唯一标识的字段。zset要求value唯一不可重复,所以当前时间戳需不需要再添加一随机数来做唯一标识待验证。

import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
 
/**
 * redis使用zset实现滑动窗口计数
 * key:sliding_window_用户登录名
 * value(zset):value=当前时间戳,score=当前时间戳
 *
 * @author zhaoshuxiang
 * @date 2022/3/2
 */
@Component
@Slf4j
public class SlidingWindowCounter {
    /**
     * redis key前缀
     */
    private static final String SLIDING_WINDOW = "sliding_window_";
    @Autowired
    private RedisTemplate redisTemplate;
     * 判断key的value中的有效访问次数是否超过最大限定值maxCount
     * 判断与数量增长分开处理
     *
     * @param key            redis key
     * @param windowInSecond 窗口间隔,秒
     * @param maxCount       最大计数
     * @return 是 or 否
    public boolean overMaxCount(String key, int windowInSecond, long maxCount) {
        key = SLIDING_WINDOW + key;
        log.info("redis key = {}", key);
        // 当前时间
        long currentMs = System.currentTimeMillis();
        // 窗口开始时间
        long windowStartMs = currentMs - windowInSecond * 1000L;
        // 按score统计key的value中的有效数量
        Long count = redisTemplate.opsForZSet().count(key, windowStartMs, currentMs);
        // 已访问次数 >= 最大可访问值
        return count >= maxCount;
    }
     * 判断key的value中的有效访问次数是否超过最大限定值maxCount,若没超过,调用increment方法,将窗口内的访问数加一
     * 判断与数量增长同步处理
     * @return 可访问 or 不可访问
    public boolean canAccess(String key, int windowInSecond, long maxCount) {
        //按key统计集合中的有效数量
        Long count = redisTemplate.opsForZSet().zCard(key);
        if (count < maxCount) {
            increment(key, windowInSecond);
            return true;
        } else {
            return false;
        }
     * 滑动窗口计数增长
    public void increment(String key, Integer windowInSecond) {
        long windowStartMs = currentMs - windowInSecond * 1000;
        // 单例模式(提升性能)
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        // 清除窗口过期成员
        zSetOperations.removeRangeByScore(key, 0, windowStartMs);
        // 添加当前时间 value=当前时间戳 score=当前时间戳
        zSetOperations.add(key, String.valueOf(currentMs), currentMs);
        // 设置key过期时间
        redisTemplate.expire(key, windowInSecond, TimeUnit.SECONDS);
}

补充:Redis zSet实现滑动窗口对短信进行防刷限流

前言

  主要针对目前线上短信被脚本恶意盗刷的情况,用Redis实现滑动窗口限流

示例代码

public void checkCurrentWindowValue(String telNum) {
        
        String windowKey = CommonConstant.getNnSmsWindowKey(telNum);
        //获取当前时间戳
        long currentTime = System.currentTimeMillis();
        //1小时,默认只能发5次,参数smsWindowMax做成可配置项,配置到Nacos配置中心,可以动态调整
        if (RedisUtil.hasKey(windowKey)) {
            //参数smsWindowTime表示限制的窗口时间
            //这里获取当前时间与限制窗口时间之间的短信发送次数
            Optional<Long> optional = Optional.ofNullable(RedisUtil.zCount(windowKey, currentTime - smsWindowTime, currentTime));
            if (optional.isPresent()) {
                long count = optional.get();
                if (count >= smsWindowMax) {
                    log.error("==========>当前号码:{} 短信发送太频繁,{}", telNum, count);
                    throw new ServiceException(MidRetCode.umid_10060);
                }
            }
        }
        StringBuilder sb =new StringBuilder();
        String windowEle = sb.append(telNum).append(":").append(currentTime).toString();
        //添加当前发送元素到zSet中(由于保证元素唯一,这里将元素加上了当前时间戳)
        RedisUtil.zAdd(windowKey, windowEle, currentTime);
        //设置2倍窗口Key:windowKey 的过期时间
        RedisUtil.expire(windowKey, smsWindowTime*2, TimeUnit.MILLISECONDS);
    }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们