JAVA基于Redis實現(xiàn)計數(shù)器限流的使用示例
1、簡述
在現(xiàn)實世界中可能會出現(xiàn)服務(wù)器被虛假請求轟炸的情況,因此您可能希望控制這種虛假的請求。
一些實際使用情形可能如下所示:
API配額管理-作為提供者,您可能希望根據(jù)用戶的付款情況限制向服務(wù)器發(fā)出API請求的速率。這可以在客戶端或服務(wù)端實現(xiàn)。
安全性-防止DDOS攻擊。
成本控制–這對服務(wù)方甚至客戶方來說都不是必需的。如果某個組件以非常高的速率發(fā)出一個事件,它可能有助于控制它,它可能有助于控制從客戶端發(fā)送的請求。
常見的限流算法:令牌桶算法, 漏桶算法。比較成熟的有分布式hystrix, sentinel,還有g(shù)uava高并發(fā)限流ratelimiter。本文主要是介紹Redis如何對指定的key進行計數(shù)限流的。
2、引用和配置
引用redis的maven包,包括客戶端連接插件jedis。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
在application.yml配置中添加Redis服務(wù)端配置:
spring: #redis配置# redis: database: 0 host: 192.168.254.128 port: 6379 password: 123456 timeout: 5000 jedis: pool: max-active: 8 max-wait: 5000 max-idle: 8 min-idle: 1
3、Config配置
添加redis configuration配置bean和redis存儲json轉(zhuǎn)換。
@Configuration public class MyRedisConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.password}") private String password; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.database}") private int database; //@SuppressWarnings("all") @Bean public StringRedisTemplate redisTemplate(RedisConnectionFactory factory){ StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); RedisSerializer stringSerializer = new StringRedisSerializer(); template.setKeySerializer(stringSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(stringSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } @Bean public JedisConnectionFactory jedisConnectionFactory() { RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(); configuration.setHostName(host); configuration.setPassword(RedisPassword.of(password)); configuration.setPort(port); configuration.setDatabase(database); JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(configuration); jedisConnectionFactory.getPoolConfig().setMaxIdle(30); jedisConnectionFactory.getPoolConfig().setMinIdle(10); return jedisConnectionFactory; } }
4、添加組件
添加自定義的限速攔截器組件,到時候攔截器會根據(jù)該組件注釋來攔截對應(yīng)的接口請求,實現(xiàn)跟業(yè)務(wù)解耦。
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface RequestLimit { /** * 調(diào)用方唯一key的名字 * * @return */ String name(); /** * 限制訪問次數(shù) * @return */ int limitTimes(); /** * 限制時長,也就是計數(shù)器的過期時間 * * @return */ long timeout(); /** * 限制時長單位 * * @return */ TimeUnit timeUnit(); }
- name :表示請求方唯一的身份參數(shù),如userId,token等。
- limitTimes :表示限制訪問次數(shù),也就是他在指定時間內(nèi)可以訪問多少次。
- timeout:表示限制訪問次數(shù)的有效期,一分鐘還是一個小時。
- timeUnit:表示限速實際的單位,秒、分鐘、小時等
5、攔截器
添加攔截器實現(xiàn)HandlerInterceptor 來實現(xiàn)對添加@RequestLimit 進行攔截處理當(dāng)前請求在規(guī)定的時間是否超出。當(dāng)前采用的是redis的BoundValueOperations 來計算請求次數(shù)在規(guī)定的時間內(nèi)是否異常。
/** * 請求限流攔截器 */ @Slf4j @Component public class RequestLimitInterceptor implements HandlerInterceptor { @Autowired private RedisTemplate redisTemplate; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(handler instanceof HandlerMethod){ HandlerMethod handlerMethod = (HandlerMethod) handler; //判斷接口是否添加requestLimit if(handlerMethod.hasMethodAnnotation(RequestLimit.class)){ RequestLimit requestLimit = handlerMethod.getMethod().getAnnotation(RequestLimit.class); JSONObject object = new JSONObject(); String token = request.getParameter(requestLimit.name()); response.setContentType("text/json;charset=utf-8"); object.put("timestamp", System.currentTimeMillis()); BoundValueOperations<String, Integer> boundValueOperations = redisTemplate.boundValueOps(token); if(StringUtils.isEmpty(token)){ object.put("result", "token is invalid"); response.getWriter().print(JSON.toJSONString(object)); } else if(checkLimit(token,requestLimit)){ object.put("result","token is success,請求成功"); long expire = boundValueOperations.getExpire(); return true; }else { object.put("result", "達到訪問次數(shù)上限,禁止訪問!"); response.getWriter().print(JSON.toJSONString(object)); } return false; } } return true; } /** * 限速校驗 * @param token * @param limit * @return */ private Boolean checkLimit(String token, RequestLimit limit){ BoundValueOperations<String , Integer> boundValueOperations = redisTemplate.boundValueOps(token); Integer count = boundValueOperations.get(); if(Objects.isNull(count)){ redisTemplate.boundValueOps(token).set(1,limit.timeout(), limit.timeUnit()); }else if(count > limit.limitTimes()){ return Boolean.FALSE; }else { redisTemplate.boundValueOps(token).set(++count, boundValueOperations.getExpire(),limit.timeUnit()); } return Boolean.TRUE; } }
實現(xiàn)攔截器后我們需要將當(dāng)前攔截器添加到WebMvcConfigurer攔截器中:
@Configuration public class MyWebConfig implements WebMvcConfigurer { @Autowired private RequestLimitInterceptor requestLimitInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(requestLimitInterceptor).addPathPatterns("/**"); WebMvcConfigurer.super.addInterceptors(registry); } }
這樣我們就完成了簡易的攔截限速器,我們在請求的接口前添加@RequestLimit就可以限速了:
/** * 分頁查詢 * @param param * @return */ @RequestLimit(name = "token", limitTimes = 20, timeout = 60, timeUnit = TimeUnit.SECONDS) @GetMapping("/page") public R page(TagParam param) { Query query = param.toQuery(); PageInfo<Tag> pageInfo = tagService.page(query); return R.ok().put("pageInfo", pageInfo); }
6、BoundValueOperations 使用
6.1 BoundValueOperations
就是一個綁定key的對象,我們可以通過這個對象來進行與key相關(guān)的操作
BoundValueOperations boundValueOps = redisTemplate.boundValueOps("token");
6.2 set(V value)
給綁定鍵重新設(shè)置值(如果沒有值,則會添加這個值)
boundValueOps.set("token");
6.3 get()
獲取綁定鍵的值。
String str = (String) boundValueOps.get(); System.out.println(str);
6.4 set(V value, long timeout, TimeUnit unit)
給綁定鍵設(shè)置新值并設(shè)置過期時間
boundValueOps.set("token",30, TimeUnit.SECONDS);
6.5 getAndSet(V value)
如果有這個值則獲取沒有則設(shè)置
String oldValue = (String) boundValueOps.getAndSet("token"); String newValue = (String) boundValueOps.get();
6.6 increment(double delta)和increment(long delta)
它是Redis的自增長鍵,前提是綁定值的類型是double或long類型。increment是單線程的,所以它是安全的。
BoundValueOperations boundValueOps = redisTemplate.boundValueOps("token"); boundValueOps.set(1); System.out.println(boundValueOps.get()); boundValueOps.increment(1); System.out.println(boundValueOps.get());
注意!使用該方法,需要使用StringRedisSerializer序列化器才能使用increment方法,否則會報錯
7、代碼地址
不管代碼實現(xiàn)方式如何,還是要自己動手來實現(xiàn)才能體驗設(shè)計的思想,讓自己成長的更快,理解的更透徹。
代碼地址:https://gitee.com/lhdxhl/redis.git
參考文章:https://zhuanlan.zhihu.com/p/427906048
到此這篇關(guān)于JAVA基于Redis實現(xiàn)計數(shù)器限流的使用示例的文章就介紹到這了,更多相關(guān)JAVA Redis計數(shù)器限流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決mybatis resultMap根據(jù)type找不到對應(yīng)的包問題
這篇文章主要介紹了解決mybatis resultMap根據(jù)type找不到對應(yīng)的包問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Java選擇結(jié)構(gòu)與循環(huán)結(jié)構(gòu)的使用詳解
循環(huán)結(jié)構(gòu)是指在程序中需要反復(fù)執(zhí)行某個功能而設(shè)置的一種程序結(jié)構(gòu)。它由循環(huán)體中的條件,判斷繼續(xù)執(zhí)行某個功能還是退出循環(huán),選擇結(jié)構(gòu)用于判斷給定的條件,根據(jù)判斷的結(jié)果判斷某些條件,根據(jù)判斷的結(jié)果來控制程序的流程2022-03-03java 過濾器filter防sql注入的實現(xiàn)代碼
下面小編就為大家?guī)硪黄猨ava 過濾器filter防sql注入的實現(xiàn)代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08ApiOperation和ApiParam注解依賴的安裝和使用以及注意事項說明
這篇文章主要介紹了ApiOperation和ApiParam注解依賴的安裝和使用以及注意事項說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09Java深入了解數(shù)據(jù)結(jié)構(gòu)之二叉搜索樹增 插 刪 創(chuàng)詳解
二叉搜索樹是以一棵二叉樹來組織的。每個節(jié)點是一個對象,包含的屬性有l(wèi)eft,right,p和key,其中,left指向該節(jié)點的左孩子,right指向該節(jié)點的右孩子,p指向該節(jié)點的父節(jié)點,key是它的值2022-01-01springboot使用logback文件查看錯誤日志過程詳解
這篇文章主要介紹了springboot使用logback文件查看錯誤日志過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09