JAVA基于Redis實(shí)現(xiàn)計(jì)數(shù)器限流的使用示例
1、簡(jiǎn)述
在現(xiàn)實(shí)世界中可能會(huì)出現(xiàn)服務(wù)器被虛假請(qǐng)求轟炸的情況,因此您可能希望控制這種虛假的請(qǐng)求。
一些實(shí)際使用情形可能如下所示:
API配額管理-作為提供者,您可能希望根據(jù)用戶(hù)的付款情況限制向服務(wù)器發(fā)出API請(qǐng)求的速率。這可以在客戶(hù)端或服務(wù)端實(shí)現(xiàn)。
安全性-防止DDOS攻擊。
成本控制–這對(duì)服務(wù)方甚至客戶(hù)方來(lái)說(shuō)都不是必需的。如果某個(gè)組件以非常高的速率發(fā)出一個(gè)事件,它可能有助于控制它,它可能有助于控制從客戶(hù)端發(fā)送的請(qǐng)求。
常見(jiàn)的限流算法:令牌桶算法, 漏桶算法。比較成熟的有分布式hystrix, sentinel,還有g(shù)uava高并發(fā)限流ratelimiter。本文主要是介紹Redis如何對(duì)指定的key進(jìn)行計(jì)數(shù)限流的。
2、引用和配置
引用redis的maven包,包括客戶(hù)端連接插件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存儲(chǔ)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、添加組件
添加自定義的限速攔截器組件,到時(shí)候攔截器會(huì)根據(jù)該組件注釋來(lái)攔截對(duì)應(yīng)的接口請(qǐng)求,實(shí)現(xiàn)跟業(yè)務(wù)解耦。
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface RequestLimit { /** * 調(diào)用方唯一key的名字 * * @return */ String name(); /** * 限制訪問(wèn)次數(shù) * @return */ int limitTimes(); /** * 限制時(shí)長(zhǎng),也就是計(jì)數(shù)器的過(guò)期時(shí)間 * * @return */ long timeout(); /** * 限制時(shí)長(zhǎng)單位 * * @return */ TimeUnit timeUnit(); }
- name :表示請(qǐng)求方唯一的身份參數(shù),如userId,token等。
- limitTimes :表示限制訪問(wèn)次數(shù),也就是他在指定時(shí)間內(nèi)可以訪問(wèn)多少次。
- timeout:表示限制訪問(wèn)次數(shù)的有效期,一分鐘還是一個(gè)小時(shí)。
- timeUnit:表示限速實(shí)際的單位,秒、分鐘、小時(shí)等
5、攔截器
添加攔截器實(shí)現(xiàn)HandlerInterceptor 來(lái)實(shí)現(xiàn)對(duì)添加@RequestLimit 進(jìn)行攔截處理當(dāng)前請(qǐng)求在規(guī)定的時(shí)間是否超出。當(dāng)前采用的是redis的BoundValueOperations 來(lái)計(jì)算請(qǐng)求次數(shù)在規(guī)定的時(shí)間內(nèi)是否異常。
/** * 請(qǐng)求限流攔截器 */ @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,請(qǐng)求成功"); long expire = boundValueOperations.getExpire(); return true; }else { object.put("result", "達(dá)到訪問(wèn)次數(shù)上限,禁止訪問(wèn)!"); response.getWriter().print(JSON.toJSONString(object)); } return false; } } return true; } /** * 限速校驗(yàn) * @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; } }
實(shí)現(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); } }
這樣我們就完成了簡(jiǎn)易的攔截限速器,我們?cè)谡?qǐng)求的接口前添加@RequestLimit就可以限速了:
/** * 分頁(yè)查詢(xún) * @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
就是一個(gè)綁定key的對(duì)象,我們可以通過(guò)這個(gè)對(duì)象來(lái)進(jìn)行與key相關(guān)的操作
BoundValueOperations boundValueOps = redisTemplate.boundValueOps("token");
6.2 set(V value)
給綁定鍵重新設(shè)置值(如果沒(méi)有值,則會(huì)添加這個(gè)值)
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è)置過(guò)期時(shí)間
boundValueOps.set("token",30, TimeUnit.SECONDS);
6.5 getAndSet(V value)
如果有這個(gè)值則獲取沒(méi)有則設(shè)置
String oldValue = (String) boundValueOps.getAndSet("token"); String newValue = (String) boundValueOps.get();
6.6 increment(double delta)和increment(long delta)
它是Redis的自增長(zhǎng)鍵,前提是綁定值的類(lèi)型是double或long類(lèi)型。increment是單線程的,所以它是安全的。
BoundValueOperations boundValueOps = redisTemplate.boundValueOps("token"); boundValueOps.set(1); System.out.println(boundValueOps.get()); boundValueOps.increment(1); System.out.println(boundValueOps.get());
注意!使用該方法,需要使用StringRedisSerializer序列化器才能使用increment方法,否則會(huì)報(bào)錯(cuò)
7、代碼地址
不管代碼實(shí)現(xiàn)方式如何,還是要自己動(dòng)手來(lái)實(shí)現(xiàn)才能體驗(yàn)設(shè)計(jì)的思想,讓自己成長(zhǎng)的更快,理解的更透徹。
代碼地址:https://gitee.com/lhdxhl/redis.git
參考文章:https://zhuanlan.zhihu.com/p/427906048
到此這篇關(guān)于JAVA基于Redis實(shí)現(xiàn)計(jì)數(shù)器限流的使用示例的文章就介紹到這了,更多相關(guān)JAVA Redis計(jì)數(shù)器限流內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot使用Maven插件進(jìn)行項(xiàng)目打包的方法
這篇文章主要介紹了SpringBoot使用Maven插件進(jìn)行項(xiàng)目打包的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11解決mybatis resultMap根據(jù)type找不到對(duì)應(yīng)的包問(wèn)題
這篇文章主要介紹了解決mybatis resultMap根據(jù)type找不到對(duì)應(yīng)的包問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08Java選擇結(jié)構(gòu)與循環(huán)結(jié)構(gòu)的使用詳解
循環(huán)結(jié)構(gòu)是指在程序中需要反復(fù)執(zhí)行某個(gè)功能而設(shè)置的一種程序結(jié)構(gòu)。它由循環(huán)體中的條件,判斷繼續(xù)執(zhí)行某個(gè)功能還是退出循環(huán),選擇結(jié)構(gòu)用于判斷給定的條件,根據(jù)判斷的結(jié)果判斷某些條件,根據(jù)判斷的結(jié)果來(lái)控制程序的流程2022-03-03java 過(guò)濾器filter防sql注入的實(shí)現(xiàn)代碼
下面小編就為大家?guī)?lái)一篇java 過(guò)濾器filter防sql注入的實(shí)現(xiàn)代碼。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-08-08ApiOperation和ApiParam注解依賴(lài)的安裝和使用以及注意事項(xiàng)說(shuō)明
這篇文章主要介紹了ApiOperation和ApiParam注解依賴(lài)的安裝和使用以及注意事項(xiàng)說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09Java深入了解數(shù)據(jù)結(jié)構(gòu)之二叉搜索樹(shù)增 插 刪 創(chuàng)詳解
二叉搜索樹(shù)是以一棵二叉樹(shù)來(lái)組織的。每個(gè)節(jié)點(diǎn)是一個(gè)對(duì)象,包含的屬性有l(wèi)eft,right,p和key,其中,left指向該節(jié)點(diǎn)的左孩子,right指向該節(jié)點(diǎn)的右孩子,p指向該節(jié)點(diǎn)的父節(jié)點(diǎn),key是它的值2022-01-01springboot使用logback文件查看錯(cuò)誤日志過(guò)程詳解
這篇文章主要介紹了springboot使用logback文件查看錯(cuò)誤日志過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09