In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use ratelimiter-spring-boot-starter current limiter". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use ratelimiter-spring-boot-starter current limiter".
Ratelimiter-spring-boot-starter
The distributed current-limiting components of partial business applications based on redis make it easy for the project to have distributed current-limiting capabilities. There are many scenarios of current restriction. The so-called current restriction generally refers to the gateway current limit to control the flood peak traffic so as not to destroy the rear application. The reason why the distributed current limit of partial business applications is highlighted here is that, different from the gateway current limit, the service side flow limit can easily achieve fine-grained traffic control according to the nature of the service. For example, the following scenarios
Case 1:
There is a public openApi interface, and openApi will dispatch an appId to the accessor. At this time, if you need to limit the appId of each accessor, it is not easy to do so, and it can only be implemented on the business side.
Case 2:
In the company's internal SMS interface, multiple third-party SMS channels are connected internally, and the traffic control of each SMS channel is different. Assuming that some third parties restrict traffic according to the combination of mobile phone number and SMS template, gateway current restriction is even more difficult.
In the scenario illustrated above, the problem of current restriction can be easily solved through ratelimiter-spring-boot-starter.
1. Get started quickly
1.1.Add component dependencies, which have been uploaded to maven central warehouse
Maven
Com.github.taptap ratelimiter-spring-boot-starter 1.0
Gradle
Implementation 'com.github.taptap:ratelimiter-spring-boot-starter:1.0'1.2, application.properties configuration spring.ratelimiter.enabled = truespring.ratelimiter.redis-address = redis://127.0.0.1:6379spring.ratelimiter.redis-password = xxx
Configurations that enable ratelimiter must be added and will not be loaded by default. Redis-related connections are not required. If Redisson is already used in your project, you do not need to configure redis connections in the current-limiting framework.
1.3.Add @ RateLimit to the method that requires flow-limiting logic, such as @ RestController@RequestMapping ("/ test") public class TestController {@ GetMapping ("/ get") @ RateLimit (rate = 5, rateInterval = "10s") public String get (String name) {return "hello";} 1.3.1 @ RateLimit
The @ RateLimit annotation can be added to any bean managed by spring, not limited to controller, but also service and repository. In the use of the most basic current-limiting function, the above three steps have been completed. @ RateLimit has two basic parameters. RateInterval sets the time window, and rate sets the number of requests allowed to pass in the time window.
1.3.2 current-limiting granularity, current-limiting key
. The granularity of current limit is done through the key of current limit. In the most basic setting, the key of current limit is spelled by method name by default. The rules are as follows:
Key = RateLimiter_ + class name + method name
In addition to the default key policy, ratelimiter-spring-boot-starter takes full account of the complexity of business current restrictions and provides a variety of ways. Combined with business characteristics, achieve more fine-grained current-limiting control.
1.3.3 behavior after triggering current limit
After the current limit is triggered by default, the program returns a response with a http status code of 429. The response value is as follows:
{"code": 429, "msg": "Too Many Requests"}
At the same time, the header of the response carries a time value of Retry-After, in ms, to tell the caller how long it will take to try again. Of course, all of this can be customized, and the advanced usage can continue to read on.
2. Advanced usage 2.1.Custom current-limiting key
There are three ways to customize the current-limiting key. When the custom current-limiting key takes effect, the current-limiting key becomes (the default key + custom key). The following examples are shown in turn.
2.1.1, @ RateLimitKey @ RestController@RequestMapping ("/ test") public class TestController {@ GetMapping ("/ get") @ RateLimit (rate = 5, rateInterval = "10s") public String get (@ RateLimitKey String name) {return "get";}}
The @ RateLimitKey annotation can be placed on the input parameter of the method, which requires that the input parameter is the underlying data type, in the above example, if name = kl. Then the key of the final current limit is as follows:
Key = RateLimiter_com.taptap.ratelimiter.web.TestController.get-kl2.1.2, specify the method of keys @ RestController@RequestMapping ("/ test") public class TestController {@ GetMapping ("/ get") @ RateLimit (rate = 5, rateInterval = "10s", keys = {"# name"}) public String get (String name) {return "get" } @ GetMapping ("/ hello") @ RateLimit (rate = 5, rateInterval = "10s", keys = {"# user.name", "user.id"}) public String hello (User user) {return "hello";}}
The parameter keys is smarter than the @ RateLimitKey annotation and can basically include the ability of @ RateLimitKey, but in simple scenarios, it is not as easy to use as @ RateLimitKey. The syntax of keys comes from the Spel of spring. You can get the attributes of the object into the parameter. You can get more than one, and finally it will be spliced together. Students who have used spring-cache may be more familiar with it. If you are not clear about the use of Spel, you can refer to the annotated document of spring-cache.
2.1.3. Custom key acquisition function @ RestController@RequestMapping ("/ test") public class TestController {@ GetMapping ("/ get") @ RateLimit (rate = 5, rateInterval = "10s", customKeyFunction = "keyFunction") public String get (String name) {return "get";} public String keyFunction (String name) {return "keyFunction" + name;}}
When the @ RateLimitKey and keys parameters cannot be satisfied, for example, the value of the input parameter is an encrypted value, and the stream is limited according to the relevant plaintext content after decryption. You can customize the function to obtain key in the same class. This function requires the same input parameters as the current-restricted method, and the return value is of type String. The return value cannot be empty. If it is empty, it will fall back to the default key acquisition policy.
2.2.2.Behavior after customizing current limit 2.2.1, configure response content spring.ratelimiter.enabled=truespring.ratelimiter.response-body=Too Many Requestsspring.ratelimiter.status-code=509
After adding the configuration above, when the current limit is triggered, the status code of the http becomes 509. The content of the response has become Too Many Requests.
2.2.2 Custom current limit triggers exception handlers
After the default trigger current limit, the current limiter will throw an exception, which is handled by an exception handler defined in the current limiter framework. To customize the current limit trigger processor, you need to disable the default current limit trigger processor of the system as follows:
Spring.ratelimiter.exceptionHandler.enable=false
Then add a custom processor to the project, as follows:
@ ControllerAdvicepublic class RateLimitExceptionHandler {private final RateLimiterProperties limiterProperties; public RateLimitExceptionHandler (RateLimiterProperties limiterProperties) {this.limiterProperties = limiterProperties;} @ ExceptionHandler (value = RateLimitException.class) @ ResponseBody public String exceptionHandler (HttpServletResponse response, RateLimitException e) {response.setStatus (limiterProperties.getStatusCode ()); response.setHeader ("Retry-After", String.valueOf (e.getRetryAfter ()); return limiterProperties.getResponseBody () } 2.2.3 Custom trigger current limit handler @ RequestMapping ("/ test") public class TestController {@ GetMapping ("/ get") @ RateLimit (rate = 5, rateInterval = "10s", fallbackFunction = "getFallback") public String get (String name) {return "get";} public String getFallback (String name) {return "Too Many Requests" + name;}}
This approach is similar to using the 2.1.3, custom key fetch function. However, one more requirement is that the type of the return value needs to be the same as that of the original current-limiting function. When the current limit is triggered, the framework will call the function configured by fallbackFunction to execute and return.
Thank you for your reading, the above is the content of "how to use ratelimiter-spring-boot-starter current limiter". After the study of this article, I believe you have a deeper understanding of how to use ratelimiter-spring-boot-starter current limiter, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.