Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the current limit of a single machine by using the speed limiter RateLimiter in SpringBoot

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

It is believed that many inexperienced people do not know what to do when SpringBoot uses the speed limiter RateLimiter to realize the current limit on a single machine. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

one。 Overview

Refer to the open source project https://github.com/xkcoding/spring-boot-demo

In the operation and maintenance of the system, sometimes in order to avoid the malicious interface of users, certain rules are added to limit the current. This Demo uses the rate limiter com.xkcoding.ratelimit.guava.annotation.RateLimiter to realize the current limit of the stand-alone version.

two。 SpringBootDemo2.1 relies on org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-aop cn.hutool hutool-all com.google.guava guava 2.2 application.ymlserver: port: 8080 servlet: context-path: / demo2.3 launch class @ SpringBootApplicationpublic class SpringBootDemoRatelimitGuavaApplication {public static void main (String [] args) {SpringApplication.run (SpringBootDemoRatelimitGuavaApplication.class) Args) Define a current-limiting annotation RateLimiter.java

Note that AliasFor is used in the code to set aliases for a set of attributes, so when you get comments, you need to obtain them through the annotation tool class AnnotationUtils provided by Spring, not through AOP parameter injection, otherwise the values of some attributes will not be set.

@ Target (ElementType.METHOD) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface RateLimiter {int NOT_LIMITED = 0; / * qps (concurrency per second) * / @ AliasFor ("qps") double value () default NOT_LIMITED; / * qps (concurrency per second) * / @ AliasFor ("value") double qps () default NOT_LIMITED / * timeout length. Do not wait for * / int timeout () default 0 by default; / * timeout unit. Default millisecond * / TimeUnit timeUnit () default TimeUnit.MICROSECONDS;} 2.5 proxy: RateLimiterAspect.java@Slf4j@Aspect@Componentpublic class RateLimiterAspect {/ * stand-alone cache * / private static final ConcurrentMap RATE_LIMITER_CACHE = new ConcurrentHashMap () @ Pointcut ("@ annotation (com.xkcoding.ratelimit.guava.annotation.RateLimiter)") public void rateLimit () {} @ Around ("rateLimit ()") public Object pointcut (ProceedingJoinPoint point) throws Throwable {MethodSignature signature = (MethodSignature) point.getSignature (); Method method = signature.getMethod (); / / obtain RateLimiter annotation RateLimiter rateLimiter = AnnotationUtils.findAnnotation (method, RateLimiter.class) through AnnotationUtils.findAnnotation If (rateLimiter! = null & & rateLimiter.qps () > RateLimiter.NOT_LIMITED) {double qps = rateLimiter.qps (); / / TODO this key can be configured according to specific needs, for example, according to ip restrictions, or user String key = method.getDeclaringClass (). GetName () + StrUtil.DOT + method.getName () If (RATE_LIMITER_CACHE.get (key) = = null) {/ / initialize QPS RATE_LIMITER_CACHE.put (key, com.google.common.util.concurrent.RateLimiter.create (qps)) } / / try to get token if (RATE_LIMITER_CACHE.get (key)! = null & &! RATE_LIMITER_CACHE.get (key) .tryAcquire (rateLimiter.timeout (), rateLimiter.timeUnit () {throw new RuntimeException ("hands are too fast, slow down ~");}} return point.proceed () Using the @ Slf4j@RestControllerpublic class TestController {/ * interface, you can only request once per second without waiting for * @ return * / @ RateLimiter (value = 1.0) @ GetMapping ("/ test1") public Dict test1 () {log.info ("[test1]] to be executed.") ; return Dict.create () .set ("msg", "hello,world!") .set ("description", "Don't try to see me all the time, don't believe you refresh it quickly ~") The} / * * interface can only request once per second, waiting for one second * @ return * / @ RateLimiter (value = 1.0, timeout = 1) timeUnit = TimeUnit.SECONDS) @ GetMapping ("/ test3") public Dict test3 () {log.info ("[test3] is executed"). ; return Dict.create (). Set ("msg", "hello,world!"). Set ("description", "Don't keep seeing me, don't believe you refresh quickly ~");}} springboot is a new programming specification for springboot, which is designed to simplify the initial construction and development process of new Spring applications. SpringBoot is also a framework that serves the framework, and the scope of services is to simplify configuration files.

After reading the above, have you mastered the method of how SpringBoot uses the speed limiter RateLimiter to limit the current on a single machine? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report