色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁技術文章
文章詳情頁

springboot+redis 實現分布式限流令牌桶的示例代碼

瀏覽:141日期:2023-03-14 15:36:59
1、前言

網上找了很多redis分布式限流方案,要不就是太大,需要引入第三方jar,而且還無法正常運行,要不就是定時任務定時往key中放入數據,使用的時候調用,嚴重影響性能,所以著手自定義實現redis令牌桶。只用到了spring-boot-starter-data-redis包,并且就幾行代碼。

2、環境準備

a、idea新建springboot項目,引入spring-data-redis包b、編寫令牌桶實現方法RedisLimitExcutorc、測試功能,創建全局攔截器,測試功能

3、上代碼

springboot+redis 實現分布式限流令牌桶的示例代碼

maven添加依賴

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>

令牌桶實現方法RedisLimitExcutor

package com.example.redis_limit_demo.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.core.script.DefaultRedisScript;import org.springframework.data.redis.core.script.RedisScript;import org.springframework.stereotype.Component;import java.util.ArrayList;import java.util.List;/** * 令牌桶實現 */@Componentpublic class RedisLimitExcutor { private StringRedisTemplate stringRedisTemplate; @Autowired public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {this.stringRedisTemplate = stringRedisTemplate; } /** * 令牌的 * * @param keykey值 * @param limitCount 容量 * @param seconds 時間間隔 * @return */ public boolean tryAccess(String key, int limitCount, int seconds) {String luaScript = buildLuaScript();RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);List<String> keys = new ArrayList<>();keys.add(key);Long count = stringRedisTemplate.execute(redisScript, keys, String.valueOf(limitCount), String.valueOf(seconds));if (count != 0) { return true;} else { return false;} } /** * 腳本 * * @return */ private static final String buildLuaScript() {StringBuilder lua = new StringBuilder();lua.append(' local key = KEYS[1]');lua.append('nlocal limit = tonumber(ARGV[1])');lua.append('nlocal curentLimit = tonumber(redis.call(’get’, key) or '0')');lua.append('nif curentLimit + 1 > limit then');lua.append('nreturn 0');lua.append('nelse');lua.append('n redis.call('INCRBY', key, 1)');lua.append('nredis.call('EXPIRE', key, ARGV[2])');lua.append('nreturn curentLimit + 1');lua.append('nend');return lua.toString(); }}

攔截器配置WebAppConfig

package com.example.redis_limit_demo.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/** * 攔截器配置 */@Configurationpublic class WebAppConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(getRequestInterceptor()).addPathPatterns('/**'); } @Bean public RequestInterceptor getRequestInterceptor() {return new RequestInterceptor(); }}

攔截器實現RequestInterceptor

package com.example.redis_limit_demo.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.net.InetAddress;import java.net.UnknownHostException;/** * 攔截器實現 */@Configurationpublic class RequestInterceptor implements HandlerInterceptor { @Autowired private RedisLimitExcutor redisLimitExcutor; /** * 只有返回true才會繼續向下執行,返回false取消當前請求 * * @param request * @param response * @param handler * @return */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {/** * 根據實際情況設置QPS */String url = request.getRequestURI();String ip = getIpAdd(request);//QPS設置為5,手動刷新接口可以測試出來if (!redisLimitExcutor.tryAccess(ip+url, 5, 1)) { throw new RuntimeException('調用頻繁');} else { return true;} } public static final String getIpAdd(HttpServletRequest request) {String ipAddress = request.getHeader('x-forwarded-for');if (ipAddress == null || ipAddress.length() == 0 || 'unknown'.equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader('Proxy-Client-IP');}if (ipAddress == null || ipAddress.length() == 0 || 'unknown'.equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader('WL-Proxy-Client-IP');}if (ipAddress == null || ipAddress.length() == 0 || 'unknown'.equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals('127.0.0.1') || ipAddress.equals('0:0:0:0:0:0:0:1')) {// 根據網卡取本機配置的IPInetAddress inet = null;try { inet = InetAddress.getLocalHost();} catch (UnknownHostException e) { return null;}ipAddress = inet.getHostAddress(); }}// 如果通過代理訪問,可能獲取2個IP,這時候去第二個(代理服務端IP)if (ipAddress.split(',').length > 1) { ipAddress = ipAddress.split(',')[1].trim();}return ipAddress; }}

測試controller

package com.example.redis_limit_demo.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RequestMapping('demo')@RestControllerpublic class DemoController { @RequestMapping('limit') public String demo() {//todo 寫業務邏輯return 'aaaaa'; }}4、運行項目,訪問接口

http://localhost:8080/demo/limit

springboot+redis 實現分布式限流令牌桶的示例代碼

當刷新頻率高了以后,就會報錯

5、碼云地址(GitHub經常訪問不到)

備注:

1、 redis的key可以根據實際情況設置,入例子中的ip+url,可以將全部流量進行控制,防止惡意刷接口,但需要注意的是,使用ip方式,要將QPS設置大一些,因為會出現整個大廈公用一個ip的情況。也可以使用url+userName,將QPS設置小一點,可以更加精準的限制api的訪問。2、可以將拋出異常進行全局捕獲和統一返回。

到此這篇關于springboot+redis 實現分布式限流令牌桶的示例代碼的文章就介紹到這了,更多相關springboot redis分布式限流令牌桶內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 久久99精品视香蕉蕉 | 奇米四色综合久久天天爱 | 久久青青草视频 | 欧美日韩亚洲综合另类ac | 日韩亚洲国产综合久久久 | 日韩在线观看中文字幕 | 久久91精品综合国产首页 | 美女视频黄在线观看 | 欧美亚洲日本国产综合网 | www色午夜 | 免费视频亚洲 | 久久有精品| 国产成人综合怡春院精品 | 亚洲欧美日本综合 | 成人男女网18免费看 | 欧美精品亚洲一区二区在线播放 | 久草在线免费播放 | 欧美日韩在线观看区一二 | 亚洲欧美另类在线视频 | 伊人久久青草青青综合 | 免费观看国产网址你懂的 | 长腿嫩模打开双腿呻吟 | 精品免费久久久久久久 | 成人免费xxx色视频 成人免费大片a毛片 | 偷偷久久 | 免费一级毛片在线播放 | 欧美一二三区在线 | 久久一区二区精品 | 高清国产美女一级a毛片录 高清国产亚洲va精品 | 久久久综合视频 | 日韩区在线观看 | 日韩成人免费在线 | 色偷偷成人网免费视频男人的天堂 | 国产精品久久久久久久hd | 99精品99| 久久在线资源 | free性欧美hd另类精品 | 二区国产 | 欧美人交性视频在线香蕉 | 国产欧美专区在线观看 | 黄影|