日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

redis?zset實現滑動窗口限流的代碼_Redis

作者:子非魚yy ? 更新時間: 2022-05-04 編程語言

限流

需求背景:同一用戶1分鐘內登錄失敗次數超過3次,頁面添加驗證碼登錄驗證,也即是限流的思想。

常見的限流算法:固定窗口計數器;滑動窗口計數器;漏桶;令牌桶。本篇選擇的滑動窗口計數器

redis zset特性

Redis 有序集合(sorted set)和集合(set)一樣也是 string 類型元素的集合,且不允許重復的成員。不同的是每個元素都會關聯一個 double 類型的分數(score)。redis 正是通過分數來為集合中的成員進行從小到大的排序。

可參考java的LinkedHashMap和HashMap,都是通過多維護變量使無序的集合變成有序的。區別是LinkedHashMap內部是多維護了2個成員變量Entry 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 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);
? ? }

原文鏈接:https://blog.csdn.net/ztx114/article/details/123235331

欄目分類
最近更新