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

redis+lua實現(xiàn)限流的項目實踐

 更新時間:2023年10月30日 15:29:28   作者:Best_Liu~  
redis有很多限流的算法(比如:令牌桶,計數(shù)器,時間窗口)等,在分布式里面進行限流的話,我們則可以使用redis+lua腳本進行限流,下面就來介紹一下redis+lua實現(xiàn)限流

1、需要引入Redis的maven坐標

<!--redis和 springboot集成的包 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.3.0.RELEASE</version>
</dependency>

2、redis配置

spring:
  # Redis數(shù)據(jù)庫索引
  redis:
    database: 0
  # Redis服務器地址
    host: 127.0.0.1
  # Redis服務器連接端口
    port: 6379
  # Redis服務器連接密碼(默認為空)
    password:
  # 連接池最大連接數(shù)(使用負值表示沒有限制)
    jedis:
      pool:
        max-active: 8
  # 連接池最大阻塞等待時間(使用負值表示沒有限制)
        max-wait: -1
  # 連接池中的最大空閑連接
        max-idle: 8
  # 連接池中的最小空閑連接
        min-idle: 0
  # 連接超時時間(毫秒)
    timeout: 10000

3、新建腳本放在該項目的 resources 目錄下,新建 limit.lua

local key = KEYS[1] --限流KEY 
local limit = tonumber(ARGV[1]) --限流大小 
local current = tonumber(redis.call('get', key) or "0") if current + 1 > limit then 
return 0 else redis.call("INCRBY", key,"1") redis.call("expire", key,"2") return current + 1 end

4、自定義限流注解

import java.lang.annotation.*;

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RedisRateLimiter {

   //往令牌桶放入令牌的速率
    double value() default  Double.MAX_VALUE;
    //獲取令牌的超時時間
    double limit() default  Double.MAX_VALUE;
}

5、自定義切面類 RedisLimiterAspect 類 ,修改掃描自己controller類

import com.imooc.annotation.RedisRateLimiter;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.assertj.core.util.Lists;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

@Aspect
@Component
public class RedisLimiterAspect {
    @Autowired
    private HttpServletResponse response;

    /**
     * 注入redis操作類
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

     private DefaultRedisScript<List> redisScript;

    /**
     * 初始化 redisScript 類
     * 返回值為 List
     */
    @PostConstruct
    public void init(){
        redisScript = new DefaultRedisScript<List>();
        redisScript.setResultType(List.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("limit.lua")));
    }

    public final static Logger log = LoggerFactory.getLogger(RedisLimiterAspect.class);

    @Pointcut("execution( public * com.zz.controller.*.*(..))")
    public void pointcut(){

    }
    @Around("pointcut()")
    public Object process(ProceedingJoinPoint proceedingJoinPoint) throws  Throwable {
        MethodSignature  signature = (MethodSignature)proceedingJoinPoint.getSignature();
        //使用Java 反射技術獲取方法上是否有@RedisRateLimiter 注解類
        RedisRateLimiter redisRateLimiter = signature.getMethod().getDeclaredAnnotation(RedisRateLimiter.class);
        if(redisRateLimiter == null){
            //正常執(zhí)行方法,執(zhí)行正常業(yè)務邏輯
            return proceedingJoinPoint.proceed();
        }
        //獲取注解上的參數(shù),獲取配置的速率
        double value = redisRateLimiter.value();
        double time = redisRateLimiter.limit();


        //list設置lua的keys[1]
        //取當前時間戳到單位秒
        String key = "ip:"+ System.currentTimeMillis() / 1000;

        List<String> keyList = Lists.newArrayList(key);

        //用戶Mpa設置Lua 的ARGV[1]
        //List<String> argList = Lists.newArrayList(String.valueOf(value));

        //調用腳本并執(zhí)行
        List result = stringRedisTemplate.execute(redisScript, keyList, String.valueOf(value),String.valueOf(time));

        log.info("限流時間段內訪問第:{} 次", result.toString());

        //lua 腳本返回 "0" 表示超出流量大小,返回1表示沒有超出流量大小
        if(StringUtils.equals(result.get(0).toString(),"0")){
            //服務降級
            fullback();
            return null;
        }

        // 沒有限流,直接放行
        return proceedingJoinPoint.proceed();
    }

    /**
     * 服務降級方法
     */
    private  void  fullback(){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer= response.getWriter();
            JSONObject o = new JSONObject();
            o.put("status",500);
            o.put("msg","Redis限流:請求太頻繁,請稍后重試!");
            o.put("data",null);
            writer.printf(o.toString()
            );

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}

6、在需要限流的類添加注解

import com.imooc.annotation.RedisRateLimiter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@Api(value = "限流", tags = {"限流測試接口"})
@RequestMapping("limiter")
public class LimiterController {

    @ApiOperation(value = "Redis限流注解測試接口",notes = "Redis限流注解測試接口", httpMethod = "GET")
    @RedisRateLimiter(value = 10, limit = 1)
    @GetMapping("/redislimit")
    public IMOOCJSONResult redislimit(){

        System.out.println("Redis限流注解測試接口");
        return IMOOCJSONResult.ok();
    }


}

到此這篇關于redis+lua實現(xiàn)限流的項目實踐的文章就介紹到這了,更多相關redis lua限流內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家! 

相關文章

  • Redis增減庫存避坑的實現(xiàn)

    Redis增減庫存避坑的實現(xiàn)

    在電商平臺或者倉庫管理系統(tǒng)中,庫存的管理是非常重要的一項任務,本文主要介紹了Redis增減庫存避坑的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2024-02-02
  • 推薦幾款 Redis 可視化工具(太厲害了)

    推薦幾款 Redis 可視化工具(太厲害了)

    這篇文章主要介紹了推薦幾款 Redis 可視化工具,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2021-04-04
  • 詳解Redis數(shù)據(jù)結構之跳躍表

    詳解Redis數(shù)據(jù)結構之跳躍表

    這篇文章主要介紹了Redis數(shù)據(jù)結構中的跳躍表的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • Redis Sentinel服務配置流程(詳解)

    Redis Sentinel服務配置流程(詳解)

    下面小編就為大家?guī)硪黄猂edis Sentinel服務配置流程(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-03-03
  • redis如何后臺啟動的方法

    redis如何后臺啟動的方法

    這篇文章主要介紹了redis如何后臺啟動的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • Redis如何從海量key中查詢出某一固定前綴的key

    Redis如何從海量key中查詢出某一固定前綴的key

    當Redis存儲一億key時,使用keys指令可能因返回全部key導致服務器卡頓,而scan指令通過游標分批獲取,避免阻塞,適合生產(chǎn)環(huán)境,需注意重復結果可用hashSet去重,count參數(shù)可調整返回數(shù)量但非強制
    2025-07-07
  • Redis概述及l(fā)inux安裝redis的詳細教程

    Redis概述及l(fā)inux安裝redis的詳細教程

    這篇文章主要介紹了Redis概述及l(fā)inux安裝redis的詳細教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-10-10
  • Redis過期Key刪除策略和內存淘汰策略的實現(xiàn)

    Redis過期Key刪除策略和內存淘汰策略的實現(xiàn)

    當內存使用達到上限,就無法存儲更多數(shù)據(jù)了,為了解決這個問題,Redis內部會有兩套內存回收的策略,過期Key刪除策略和內存淘汰策略,本文就來詳細的介紹一下這兩種方法,感興趣的可以了解一下
    2024-02-02
  • redis存儲空間復雜度和時間復雜度的平衡

    redis存儲空間復雜度和時間復雜度的平衡

    本文主要介紹了在獎品概率計算中,如何平衡內存占用和時間復雜度,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2026-02-02
  • 分段存儲Redis鍵值對的方法詳解

    分段存儲Redis鍵值對的方法詳解

    Redis是一種開源的、基于內存的數(shù)據(jù)結構存儲系統(tǒng),它可以用作數(shù)據(jù)庫、緩存和消息中間件,Redis最常用的功能之一就是其鍵值對數(shù)據(jù)模型,本文介紹針對一個value過長的鍵值對,如何分段存儲,需要的朋友可以參考下
    2025-01-01

最新評論

万年县| 竹北市| 正阳县| 温宿县| 上高县| 商丘市| 梅河口市| 山东省| 南和县| 甘南县| 拉萨市| 岳池县| 禹城市| 分宜县| 华安县| 板桥市| 蛟河市| 宜兰县| 望奎县| 兴业县| 库伦旗| 醴陵市| 新巴尔虎右旗| 松桃| 蕉岭县| 新竹市| 迁安市| 淳安县| 兴业县| 永城市| 郓城县| 高州市| 贵定县| 秦安县| 乌什县| 大关县| 五原县| 芦山县| 沙坪坝区| 芜湖市| 辛集市|