How does SpringBoot use RateLimiter to limit current through AOP?
Use RateLimiter to limit current through AOP
1. Introduction of dependencies
<!-- guava 限流 --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>25.1-jre</version> </dependency>
2. Custom annotations
@Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ServiceLimit { String description() default ""; }
3. AOP implementation class
@Component @Scope @Aspect public class LimitAspect { 每秒只发出5个令牌,此处是单进程服务的限流,内部采用令牌捅算法实现 private static RateLimiter rateLimiter = RateLimiter.create(5.0); //Service层切点 限流 @Pointcut("@annotation(com.itstyle.seckill.common.aop.ServiceLimit)") public void ServiceAspect() { } @Around("ServiceAspect()") public Object around(ProceedingJoinPoint joinPoint) { Boolean flag = rateLimiter.tryAcquire(); Object obj = null; try { if(flag){ obj = joinPoint.proceed(); } } catch (Throwable e) { e.printStackTrace(); } return obj; } }
4. Use
@Override @ServiceLimit @Transactional public Result startSeckil(long seckillId,long userId) { //todo 操作 }
SpringBoot’s current limit
Basic algorithm of current limit
Token bucket and leaky bucket
The implementation of the leaky bucket algorithm often relies on queues. When a request arrives, if the queue is not full, it is directly put into the queue, and then a processor takes out the request from the head of the queue at a fixed frequency for processing. If the request volume is large, the queue will be full, and new requests will be discarded.
Token bucket algorithm is a bucket that stores tokens with a fixed capacity, and tokens are added to the bucket at a fixed rate. There is a maximum limit for the number of tokens stored in the bucket. Once exceeded, they will be discarded or rejected. When traffic or network requests arrive, each request must obtain a token. If it can be obtained, it will be processed directly, and a token will be deleted from the token bucket. If it cannot be obtained, the request will be flow-limited and either discarded directly or waited in the buffer.
Comparison between token bucket and leaky bucket
Token bucket adds tokens to the bucket at a fixed rate , whether the request is processed depends on whether there are enough tokens in the bucket. When the number of tokens reduces to zero, new requests are rejected; leaky buckets outflow requests at a constant fixed rate, and the incoming request rate is arbitrary. When the number of incoming requests accumulates When the capacity of the leaky bucket is reached, new incoming requests are rejected;
The token bucket limits the average inflow rate and allows sudden requests. As long as there is a token, it can be processed. Support Take 3 tokens or 4 tokens at a time; the leaky bucket limits the constant outflow rate, that is, the outflow rate is a fixed constant value, for example, it always flows out at a rate of 1, but it cannot be 1 once and 2 next time. Thereby smoothing the burst inflow rate;
The token bucket allows a certain degree of burst, while the main purpose of the leaky bucket is to smooth the outflow rate;
Guava RateLimiter
1. Dependency
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>28.1-jre</version> <optional>true</optional> </dependency>
2. Sample code
@Slf4j @Configuration public class RequestInterceptor implements HandlerInterceptor { // 根据字符串分不同的令牌桶, 每天自动清理缓存 private static LoadingCache<String, RateLimiter> cachesRateLimiter = CacheBuilder.newBuilder() .maximumSize(1000) //设置缓存个数 /** * expireAfterWrite是在指定项在一定时间内没有创建/覆盖时,会移除该key,下次取的时候从loading中取 * expireAfterAccess是指定项在一定时间内没有读写,会移除该key,下次取的时候从loading中取 * refreshAfterWrite是在指定时间内没有被创建/覆盖,则指定时间过后,再次访问时,会去刷新该缓存,在新值没有到来之前,始终返回旧值 * 跟expire的区别是,指定时间过后,expire是remove该key,下次访问是同步去获取返回新值; * 而refresh则是指定时间后,不会remove该key,下次访问会触发刷新,新值没有回来时返回旧值 */ .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<String, RateLimiter>() { @Override public RateLimiter load(String key) throws Exception { // 新的字符串初始化 (限流每秒2个令牌响应) return RateLimiter.create(2); } }); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("request请求地址path[{}] uri[{}]", request.getServletPath(), request.getRequestURI()); try { String str = "hello"; // 令牌桶 RateLimiter rateLimiter = cachesRateLimiter.get(str); if (!rateLimiter.tryAcquire()) { System.out.println("too many requests."); return false; } } catch (Exception e) { // 解决拦截器的异常,全局异常处理器捕获不到的问题 request.setAttribute("exception", e); request.getRequestDispatcher("/error").forward(request, response); } return true; } }
3. Test
@RestController @RequestMapping(value = "user") public class UserController { @GetMapping public Result test2(){ System.out.println("1111"); return new Result(true,200,""); } }
http://localhost:8080/user/
If there is no result class, you can just return a string
4. Test results
Others
Create
RateLimiter provides two factory methods:
One is smooth burst Current limiting
RateLimiter r = RateLimiter.create(5); //项目启动,直接允许5个令牌
One is smooth preheating current limiting
RateLimiter r = RateLimiter.create(2, 3, TimeUnit.SECONDS); //项目启动后3秒后才会到达设置的2个令牌
Disadvantages
RateLimiter can only be used for single-machine current limiting, if you want a cluster For current limiting, you need to introduce redis or Alibaba's open source sentinel middleware.
TimeUnit.SECONDS);` //项目启动后3秒后才会到达设置的2个令牌
The above is the detailed content of How does SpringBoot use RateLimiter to limit current through AOP?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic
