最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Redis 多規(guī)則限流和防重復提交方案實現(xiàn)小結

 更新時間:2025年02月06日 10:14:27   作者:A塵埃  
本文主要介紹了Redis 多規(guī)則限流和防重復提交方案實現(xiàn)小結,包括使用String結構和Zset結構來記錄用戶IP的訪問次數(shù),具有一定的參考價值,感興趣的可以了解一下

Redis 如何實現(xiàn)限流的,但是大部分都有一個缺點,就是只能實現(xiàn)單一的限流,比如 1 分鐘訪問 1 次或者 60 分鐘訪問 10 次這種,
但是如果想一個接口兩種規(guī)則都需要滿足呢,項目又是分布式項目,應該如何解決,下面就介紹一下 Redis 實現(xiàn)分布式多規(guī)則限流的方式。

  • 如何一分鐘只能發(fā)送一次驗證碼,一小時只能發(fā)送 10 次驗證碼等等多種規(guī)則的限流;
  • 如何防止接口被惡意打擊(短時間內大量請求);
  • 如何限制接口規(guī)定時間內訪問次數(shù)。

一:使用 String 結構記錄固定時間段內某用戶 IP 訪問某接口的次數(shù)

  • RedisKey = prefix : className : methodName
  • RedisVlue = 訪問次數(shù)

攔截請求:

  • 初次訪問時設置 [RedisKey] [RedisValue=1] [規(guī)定的過期時間];
  • 獲取 RedisValue 是否超過規(guī)定次數(shù),超過則攔截,未超過則對 RedisKey 進行加1。

規(guī)則是每分鐘訪問 1000 次

  • 假設目前 RedisKey => RedisValue 為 999;
  • 目前大量請求進行到第一步( 獲取 Redis 請求次數(shù) ),那么所有線程都獲取到了值為999,進行判斷都未超過限定次數(shù)則不攔截,導致實際次數(shù)超過 1000 次
  • 解決辦法: 保證方法執(zhí)行原子性(加鎖、Lua)。

考慮在臨界值進行訪問

在這里插入圖片描述

二:使用 Zset 進行存儲,解決臨界值訪問問題

在這里插入圖片描述

三:實現(xiàn)多規(guī)則限流

①、先確定最終需要的效果(能實現(xiàn)多種限流規(guī)則+能實現(xiàn)防重復提交)

@RateLimiter(
        rules = {
                // 60秒內只能訪問10次
                @RateRule(count = 10, time = 60, timeUnit = TimeUnit.SECONDS),
                // 120秒內只能訪問20次
                @RateRule(count = 20, time = 120, timeUnit = TimeUnit.SECONDS)

        },
        // 防重復提交 (5秒鐘只能訪問1次)
        preventDuplicate = true
)

②、注解編寫

RateLimiter 注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RateLimiter {

    /**
     * 限流key
     */
    String key() default RedisKeyConstants.RATE_LIMIT_CACHE_PREFIX;

    /**
     * 限流類型 ( 默認 Ip 模式 )
     */
    LimitTypeEnum limitType() default LimitTypeEnum.IP;

    /**
     * 錯誤提示
     */
    ResultCode message() default ResultCode.REQUEST_MORE_ERROR;

    /**
     * 限流規(guī)則 (規(guī)則不可變,可多規(guī)則)
     */
    RateRule[] rules() default {};

    /**
     * 防重復提交值
     */
    boolean preventDuplicate() default false;

    /**
     * 防重復提交默認值
     */
    RateRule preventDuplicateRule() default @RateRule(count = 1, time = 5);
}

RateRule 注解:

@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RateRule {

    /**
     * 限流次數(shù)
     */
    long count() default 10;

    /**
     * 限流時間
     */
    long time() default 60;

    /**
     * 限流時間單位
     */
    TimeUnit timeUnit() default TimeUnit.SECONDS;

}

③、攔截注解 RateLimiter

  • 確定 Redis 存儲方式
    RedisKey = prefix : className : methodName
    RedisScore = 時間戳
    RedisValue = 任意分布式不重復的值即可
  • 編寫生成 RedisKey 的方法
public String getCombineKey(RateLimiter rateLimiter, JoinPoint joinPoint) {
    StringBuffer key = new StringBuffer(rateLimiter.key());
    // 不同限流類型使用不同的前綴
    switch (rateLimiter.limitType()) {
        // XXX 可以新增通過參數(shù)指定參數(shù)進行限流
        case IP:
            key.append(IpUtil.getIpAddr(((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest())).append(":");
            break;
        case USER_ID:
            SysUserDetails user = SecurityUtil.getUser();
            if (!ObjectUtils.isEmpty(user)) key.append(user.getUserId()).append(":");
            break;
        case GLOBAL:
            break;
    }
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    Class<?> targetClass = method.getDeclaringClass();
    key.append(targetClass.getSimpleName()).append("-").append(method.getName());
    return key.toString();
}

④、編寫Lua腳本(兩種將事件添加到Redis的方法)

Ⅰ:UUID(可用其他有相同的特性的值)為 Zset 中的 value 值

  • 參數(shù)介紹:
    KEYS[1] = prefix : ? : className : methodName
    KEYS[2] = 唯一ID
    KEYS[3] = 當前時間
    ARGV = [次數(shù),單位時間,次數(shù),單位時間, 次數(shù), 單位時間 …]
  • 由 Java傳入分布式不重復的 value 值
-- 1. 獲取參數(shù)
local key = KEYS[1]
local uuid = KEYS[2]
local currentTime = tonumber(KEYS[3])
-- 2. 以數(shù)組最大值為 ttl 最大值
local expireTime = -1;
-- 3. 遍歷數(shù)組查看是否超過限流規(guī)則
for i = 1, #ARGV, 2 do
    local rateRuleCount = tonumber(ARGV[i])
    local rateRuleTime = tonumber(ARGV[i + 1])
    -- 3.1 判斷在單位時間內訪問次數(shù)
    local count = redis.call('ZCOUNT', key, currentTime - rateRuleTime, currentTime)
    -- 3.2 判斷是否超過規(guī)定次數(shù)
    if tonumber(count) >= rateRuleCount then
        return true
    end
    -- 3.3 判斷元素最大值,設置為最終過期時間
    if rateRuleTime > expireTime then
        expireTime = rateRuleTime
    end
end
-- 4. redis 中添加當前時間
redis.call('ZADD', key, currentTime, uuid)
-- 5. 更新緩存過期時間
redis.call('PEXPIRE', key, expireTime)
-- 6. 刪除最大時間限度之前的數(shù)據(jù),防止數(shù)據(jù)過多
redis.call('ZREMRANGEBYSCORE', key, 0, currentTime - expireTime)
return false

Ⅱ、根據(jù)時間戳作為 Zset 中的 value 值

  • 參數(shù)介紹
    KEYS[1] = prefix : ? : className : methodName
    KEYS[2] = 當前時間
    ARGV = [次數(shù),單位時間,次數(shù),單位時間, 次數(shù), 單位時間 …]
  • 根據(jù)時間進行生成 value 值,考慮同一毫秒添加相同時間值問題
    以下為第二種實現(xiàn)方式,在并發(fā)高的情況下效率低,value 是通過時間戳進行添加,但是訪問量大的話會使得一直在調用 redis.call(‘ZADD’, key, currentTime, currentTime),但是在不沖突 value 的情況下,會比生成 UUID 好。
-- 1. 獲取參數(shù)
local key = KEYS[1]
local currentTime = KEYS[2]
-- 2. 以數(shù)組最大值為 ttl 最大值
local expireTime = -1;
-- 3. 遍歷數(shù)組查看是否越界
for i = 1, #ARGV, 2 do
    local rateRuleCount = tonumber(ARGV[i])
    local rateRuleTime = tonumber(ARGV[i + 1])
    -- 3.1 判斷在單位時間內訪問次數(shù)
    local count = redis.call('ZCOUNT', key, currentTime - rateRuleTime, currentTime)
    -- 3.2 判斷是否超過規(guī)定次數(shù)
    if tonumber(count) >= rateRuleCount then
        return true
    end
    -- 3.3 判斷元素最大值,設置為最終過期時間
    if rateRuleTime > expireTime then
        expireTime = rateRuleTime
    end
end
-- 4. 更新緩存過期時間
redis.call('PEXPIRE', key, expireTime)
-- 5. 刪除最大時間限度之前的數(shù)據(jù),防止數(shù)據(jù)過多
redis.call('ZREMRANGEBYSCORE', key, 0, currentTime - expireTime)
-- 6. redis 中添加當前時間  ( 解決多個線程在同一毫秒添加相同 value 導致 Redis 漏記的問題 )
-- 6.1 maxRetries 最大重試次數(shù) retries 重試次數(shù)
local maxRetries = 5
local retries = 0
while true do
    local result = redis.call('ZADD', key, currentTime, currentTime)
    if result == 1 then
        -- 6.2 添加成功則跳出循環(huán)
        break
    else
        -- 6.3 未添加成功則 value + 1 再次進行嘗試
        retries = retries + 1
        if retries >= maxRetries then
            -- 6.4 超過最大嘗試次數(shù) 采用添加隨機數(shù)策略
            local random_value = math.random(1, 1000)
            currentTime = currentTime + random_value
        else
            currentTime = currentTime + 1
        end
    end
end

return false

⑤、編寫AOP攔截

@Autowired
private RedisTemplate<String, Object> redisTemplate;

@Autowired
private RedisScript<Boolean> limitScript;

/**
 * 限流
 * XXX 對限流要求比較高,可以使用在 Redis中對規(guī)則進行存儲校驗 或者使用中間件
 *
 * @param joinPoint   joinPoint
 * @param rateLimiter 限流注解
 */
@Before(value = "@annotation(rateLimiter)")
public void boBefore(JoinPoint joinPoint, RateLimiter rateLimiter) {
    // 1. 生成 key
    String key = getCombineKey(rateLimiter, joinPoint);
    try {
        // 2. 執(zhí)行腳本返回是否限流
        Boolean flag = redisTemplate.execute(limitScript,
                ListUtil.of(key, String.valueOf(System.currentTimeMillis())),
                (Object[]) getRules(rateLimiter));
        // 3. 判斷是否限流
        if (Boolean.TRUE.equals(flag)) {
            log.error("ip: '{}' 攔截到一個請求 RedisKey: '{}'",
                    IpUtil.getIpAddr(((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest()),
                    key);
            throw new ServiceException(rateLimiter.message());
        }
    } catch (ServiceException e) {
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 獲取規(guī)則
 *
 * @param rateLimiter 獲取其中規(guī)則信息
 * @return
 */
private Long[] getRules(RateLimiter rateLimiter) {
    int capacity = rateLimiter.rules().length << 1;
    // 1. 構建 args
    Long[] args = new Long[rateLimiter.preventDuplicate() ? capacity + 2 : capacity];
    // 3. 記錄數(shù)組元素
    int index = 0;
    // 2. 判斷是否需要添加防重復提交到redis進行校驗
    if (rateLimiter.preventDuplicate()) {
        RateRule preventRateRule = rateLimiter.preventDuplicateRule();
        args[index++] = preventRateRule.count();
        args[index++] = preventRateRule.timeUnit().toMillis(preventRateRule.time());
    }
    RateRule[] rules = rateLimiter.rules();
    for (RateRule rule : rules) {
        args[index++] = rule.count();
        args[index++] = rule.timeUnit().toMillis(rule.time());
    }
    return args;
}

到此這篇關于Redis 多規(guī)則限流和防重復提交方案實現(xiàn)小結的文章就介紹到這了,更多相關Redis 多規(guī)則限流和防重復提交內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家! 

相關文章

  • 解析Redis未授權訪問漏洞復現(xiàn)與利用危害

    解析Redis未授權訪問漏洞復現(xiàn)與利用危害

    這篇文章主要介紹了Redis未授權訪問漏洞復現(xiàn)與利用,介紹了redis未授權訪問漏洞的基本概念及漏洞的危害,本文給大家介紹的非常詳細,需要的朋友可以參考下
    2022-01-01
  • Redis命令處理過程源碼解析

    Redis命令處理過程源碼解析

    這篇文章主要介紹了Redis命令處理過程源碼解析,本文是基于社區(qū)版redis4.0.8,通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-02-02
  • Redis連接錯誤的情況總結分析

    Redis連接錯誤的情況總結分析

    這篇文章主要給大家總結介紹了關于Redis連接錯誤的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-02-02
  • Redis的Cluster集群搭建的實現(xiàn)步驟

    Redis的Cluster集群搭建的實現(xiàn)步驟

    本文檔只對Redis的Cluster集群做簡單的介紹,并沒有對分布式系統(tǒng)的所涉及到的概念做深入的探討。感興趣的小伙伴們可以參考一下
    2021-07-07
  • RedisDesktopManager?連接redis的方法

    RedisDesktopManager?連接redis的方法

    這篇文章主要介紹了RedisDesktopManager?連接redis,需要的朋友可以參考下
    2023-08-08
  • AOP?Redis自定義注解實現(xiàn)細粒度接口IP訪問限制

    AOP?Redis自定義注解實現(xiàn)細粒度接口IP訪問限制

    這篇文章主要為大家介紹了AOP?Redis自定義注解實現(xiàn)細粒度接口IP訪問限制,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-10-10
  • 如何保證Redis與數(shù)據(jù)庫的數(shù)據(jù)一致性

    如何保證Redis與數(shù)據(jù)庫的數(shù)據(jù)一致性

    這篇文章主要介紹了如何保證Redis與數(shù)據(jù)庫的數(shù)據(jù)一致性,文中舉了兩個場景例子介紹的非常詳細,需要的朋友可以參考下
    2023-05-05
  • Redis 單機安裝和哨兵模式集群安裝的實現(xiàn)

    Redis 單機安裝和哨兵模式集群安裝的實現(xiàn)

    本文主要介紹了Redis 單機安裝和哨兵模式集群安裝的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • caffeine_redis自定義二級緩存

    caffeine_redis自定義二級緩存

    這篇文章詳細介紹了caffeine_redis 自定義二級緩存,文中有相關的背景前提與出現(xiàn)的問題,感興趣的同學可以參考一下
    2023-04-04
  • redis3.2配置文件redis.conf詳細說明

    redis3.2配置文件redis.conf詳細說明

    redis3.2配置詳解,Redis啟動的時候,可以指定配置文件,詳細說明請看本文說明
    2018-03-03

最新評論

腾冲县| 湘潭县| 修文县| 沽源县| 峨眉山市| 县级市| 甘泉县| 华宁县| 临颍县| 乐都县| 茶陵县| 辽阳县| 岑巩县| 太和县| 竹北市| 从化市| 侯马市| 阳新县| 囊谦县| 顺昌县| 中江县| 大连市| 建瓯市| 奇台县| 漳浦县| 渭源县| 绥中县| 林甸县| 徐闻县| 台南县| 定兴县| 祁门县| 北海市| 沙湾县| 喀喇| 同江市| 平邑县| 灌阳县| 和林格尔县| 新龙县| 湟源县|