In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Many novices are not very clear about how to use @ SentinelResource annotations to flexibly define control resources and how to configure control strategies. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can gain something.
In practical application, we may need to limit the current level not only to the interface. You may want to control the call to a method and the call to an external resource. Well, at this time, we have to manually define the resource points that need to limit the flow, and configure the relevant flow-limiting policies and so on.
Custom resource point
The following example is based on the fact that you have introduced Spring Cloud Alibaba Sentinel. If you don't know how to do this, it is recommended to read "using Sentinel to limit the flow of interfaces" first.
Step 1: add the configuration supported by annotations in the application main class:
@ SpringBootApplicationpublic class TestApplication {public static void main (String [] args) {SpringApplication.run (TestApplication.class, args);} / / Annotation supported configuration Bean @ Bean public SentinelResourceAspect sentinelResourceAspect () {return new SentinelResourceAspect ();}}
Step 2: use @ SentinelResource annotations where you need to control traffic through Sentinel, for example, take a method of controlling Service logic layer as an example:
@ Slf4j@Servicepublic class TestService {@ SentinelResource (value = "doSomeThing") public void doSomeThing (String str) {log.info (str);}}
At this point, a method that needs to be protected is defined. Let's talk about how to implement different protection strategies after defining the resource points, including current limitation, degradation and so on.
How to realize current limiting and fuse degradation
After defining the resource point, we can use Dashboard to set the current limit and downgrade policy to protect the resource point. At the same time, you can also use @ SentinelResource to specify the exception handling strategy in the event of current limiting and degradation. Next, let's take a look at how current limiting and downgrading are achieved.
Realize current limiting control
Step 1: call this protected method in the Web layer:
@ RestControllerpublic class TestController {@ Autowired private TestService testService; @ GetMapping ("/ hello") public String hello () {estService.doSomeThing ("hello" + new Date ()); return "didispace.com";}}
Step 2: start the test application and start Sentinel-Dashboard. Send a request to the / hello interface so that several control points shown in the following figure can be seen on the Sentinel-Dashboard:
As you can see, in addition to having a / hello resource point as in the previous starter example, there is an additional doSomeThing resource point. You can set current-limiting rules for this resource point through the interface, such as setting its QPS to 2. Since no current limit rule is set for / hello resources, you can directly simulate and call doSomeThing resources to observe whether the current limit rules take effect as long as you request the / hello API.
Below, you can call the / hello API through any tool you like. As long as the QPS exceeds 2, the following error will be returned, indicating that the current restriction policy is in effect.
At this point, the console of the server will also have the corresponding current limit error log:
2019-06-27 11 c.d.a.sentinel.service.TestService 30 aaa2019 43.514 INFO 36898-[nio-8001-exec-3] c.d.a.sentinel.service.TestService: aaa2019-06-27 11 11 c.d.a.sentinel.service.TestService 30 ERROR 36898-[nio-8001-exec-4] o.a.c.c.C. [dispatcherServlet]: Servlet.service () for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed Nested exception is java.lang.reflect.UndeclaredThrowableException] with root causecom.alibaba.csp.sentinel.slots.block.flow.FlowException: null implements exception handling of current limit
By default, Sentinel's current-limiting handling of control resources directly throws an exception, that is, the log content posted in the previous section. This can be done without reasonable business acceptance or front-end docking, but under normal circumstances, in order to achieve better user business, we will achieve some special processing after being restricted, and we do not want to show a blunt error report. Then you only need to do some processing based on the above example, such as:
Slf4j@Servicepublic class TestService {@ SentinelResource (value = "doSomeThing", blockHandler = "exceptionHandler") public void doSomeThing (String str) {log.info (str);} / / current limiting and blocking handling public void exceptionHandler (String str, BlockException ex) {log.error ("blockHandler:" + str, ex);}}
Two main things have been done:
Make specific handling functions through the blockHandler attribute of the @ SentinelResource annotation
Implement the handler function, which must pass the same parameters as the resource point, and finally add the BlockException exception parameter; at the same time, the return type must be the same.
If you are familiar with Hystrix, you should find that such a design is similar to the definition of fallback in HystrixCommand and is easy to understand.
After completing the above changes, try to access the API (note that the current limit rules need to be configured). In this case, the frontend will not return exception information, and the backend will print the log output defined in exceptionHandler. In practical application, as long as the current limit request is cached or prompted by the front end according to the business needs, it can be realized based on this method.
Realize fuse degradation
The @ SentinelResource annotation can not only be used for current limiting control, but also implement a circuit breaker degradation strategy similar to that of Hystrix. Let's take a look at how to use it.
Step 1: as with current limit control, mark resource points with @ SentinelResource annotations, such as:
@ Slf4j@Servicepublic class TestService {@ SentinelResource (value = "doSomeThing2") public void doSomeThing2 (String str) {log.info (str); throw new RuntimeException ("exception occurs");}}
Here you create a new method in the TestService class and use @ SentinelResource to name the resource doSomeThing2. This method throws an exception to tie in with the subsequent development of a downgrade strategy based on the exception ratio (similar to Hystrix). Sentinel is richer than Hystrix, and there are downgrade strategies based on response time and the number of exceptions.
Step 2: call this protected method at the Web layer:
@ RestControllerpublic class TestController {@ Autowired private TestService testService; @ GetMapping ("/ hello2") public String hello2 () {testService.doSomeThing2 ("hello2" + new Date ()); return "didispace.com";}}
Step 3: start the test application and start Sentinel-Dashboard. Send a request to the / hello2 interface so that the resource point named doSomeThing2 can be seen on the Sentinel-Dashboard. Then click the downgrade button to set the demotion rule for the resource. The exception proportion strategy is used here, the ratio is set to 0.5 (that is, 50% exception rate), and the time window is set to 2 (seconds).
Step 4: verify the circuit breaker degradation. According to the above degradation policy configuration, when the call to the doSomeThing2 method QPS > = 5, if the exception rate exceeds 50%, then the call within the next 2 seconds will directly start the circuit breaker degradation, and a DegradeException exception will be thrown directly by default, such as:
2019-06-27 17 o.a.c.c.C 49dispatcherServlet 58.913 ERROR 99863-[nio-8001-exec-2] o.a.c.c.C. [/]. [dispatcherServlet]: Servlet.service () for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.reflect.UndeclaredThrowableException] with root causecom.alibaba.csp.sentinel.slots.block.degrade.DegradeException: degraded treatment of null fuse
The downgrade method for defining a fuse in Sentinel is very simple, very similar to Hystrix. You only need to use the fallback attribute of the @ SentinelResource annotation to specify a specific method name. It should also be noted here that the return of the participants must be consistent. For example:
@ Slf4j@Servicepublic class TestService {/ / fuse and degradation treatment @ SentinelResource (value = "doSomeThing2", fallback = "fallbackHandler") public void doSomeThing2 (String str) {log.info (str); throw new RuntimeException ("exception occurs");} public void fallbackHandler (String str) {log.error ("fallbackHandler:" >)
After completing the above modification, restart the application and set the circuit breaker downgrade policy for doSomeThing2 resources (using the exception percentage), and then frequently request the / hello2 interface. Since the API keeps throwing exceptions after QPS > = 5, the condition of fuse degradation must be met. At this time, the fallbackHandler method will be executed and the log will be printed as follows:
2019-06-27 23 c.d.a.sentinel.service.TestService 44fallbackHandler:hello2 Thu Jun 19.432 ERROR 58471-[nio-8001-exec-1] c.d.a.sentinel.service.TestService: fallbackHandler:hello2 Thu Jun 27 23:44:19 CST 20192019-06-27 23 CST 4499 ERROR 58471-[nio-8001-exec-2] c.d.a.sentinel.service.TestService: fallbackHandler:hello2 Thu Jun 27 23:44:19 CST 20192019-06-27 232344 fallbackHandler:hello2 Thu Jun 19.791 ERROR 58471-[nio-8001-exec-3] c.d.a.sentinel.service.TestService: fallbackHandler:hello2 Thu Jun 27 23:44:19 CST 20192019-06-27 23 CST 44 fallbackHandler:hello2 Thu Jun 19.975 ERROR 58471-[nio-8001-exec-4] c.d.a.sentinel.service.TestService: fallbackHandler:hello2 Thu Jun 27 23:44:19 CST 20192019-06-27 23 c.d.a.sentinel.service.TestService 4420.168 ERROR 58471-- [nio-8001-exec] -5] c.d.a.sentinel.service.TestService: fallbackHandler:hello2 Thu Jun 27 23:44:20 CST 2019 more comments attribute description
The specific use cases for the two main uses of the @ SentinelResource annotation: current limiting control and fuse degradation are introduced. In addition, this note also has some other more refined configurations, such as configuration that ignores some exceptions, default degradation function, and so on, as described below:
Value: resource name, required (cannot be empty)
EntryType:entry type, optional (default is EntryType.OUT)
BlockHandler / blockHandlerClass: blockHandler corresponds to the name of the function that handles BlockException. Optional. The access scope of the blockHandler function needs to be public, the return type needs to match the original method, the parameter type needs to match the original method, and finally an additional parameter is added, the type is BlockException. The blockHandler function needs to be in the same class as the original method by default. If you want to use a function of another class, you can specify blockHandlerClass as the Class object of the corresponding class. Note that the corresponding function must be a static function, otherwise it cannot be parsed.
The fallback:fallback function name, optional, is used to provide fallback handling logic when an exception is thrown. The fallback function can handle all types of exceptions (except those excluded from exceptionsToIgnore). Fallback function signature and location requirements:
The return value type must be the same as the original function return value type
The method parameter list needs to be consistent with the original function, or an additional parameter of type Throwable can be used to receive the corresponding exception.
The fallback function needs to be in the same class as the original method by default. If you want to use a function of another class, you can specify fallbackClass as the Class object of the corresponding class. Note that the corresponding function must be a static function, otherwise it cannot be parsed.
DefaultFallback (since 1.6.0): the default fallback function name, optional, is usually used for general fallback logic (that is, it can be used for many services or methods). The default fallback function handles all types of exceptions (except those excluded from exceptionsToIgnore). If both fallback and defaultFallback are configured, only fallback will take effect. DefaultFallback function signature requirements:
The return value type must be the same as the original function return value type
The method parameter list needs to be empty, or an additional parameter of type Throwable can be used to receive the corresponding exception.
The defaultFallback function needs to be in the same class as the original method by default. If you want to use a function of another class, you can specify fallbackClass as the Class object of the corresponding class. Note that the corresponding function must be a static function, otherwise it cannot be parsed.
ExceptionsToIgnore (since 1.6.0): used to specify which exceptions are excluded, will not be counted in the exception statistics, will not be entered into the fallback logic, but will be thrown as is.
> Note: the fallback function before 1.6.0 only handles degraded exceptions (DegradeException), not business exceptions.
In particular, if both blockHandler and fallback are configured, it will only enter the blockHandler processing logic when it is degraded by current restriction and thrown out of BlockException. If blockHandler, fallback and defaultFallback are not configured, the BlockException will be thrown directly when the current is degraded.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.