The notes and a one-stop limiting fuse downgrade: @SentinelResource

In the previous "Using Sentinel implement the interface limiting" article, we rely only on the introduction of Spring Cloud Alibaba integration package to the Sentinel spring-cloud-starter-alibaba-sentinel, to complete the current limit control of all Spring MVC interfaces. However, in the actual application process, we may need to limit the flow level is not limited to the interface. Possible to call a method of limiting, to a certain limiting calls to external resources and so want to do control. What resources point of it, this time we have to manually define the required current limit, and configure the relevant content of the current-limiting strategies.

Today this we have to learn together about how to use @SentinelResourceannotations to define flexible control over resources and how to configure policies.

Custom resource points

The following example is based on that you have introduced Spring Cloud Alibaba Sentinel basis, if you have not these, recommended that priority be read "Using the Sentinel interface to achieve current limiting" .

The first step: Add notes in the main application class supported configurations:

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    // 注解支持的配置Bean
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

}
复制代码

Step 2: Use where necessary to control the flow through the Sentinel @SentinelResourcenotes, such as the following to a method of controlling Service logic layer, for example:

@Slf4j
@Service
public class TestService {

    @SentinelResource(value = "doSomeThing")
    public void doSomeThing(String str) {
        log.info(str);
    }

}
复制代码

Here need to be protected to a method definition is complete. Here we were to talk about after the defined resource points, we realize how different protection strategies, including: limiting, demotion and so on.

How to achieve current-limiting fuse with a demotion

After defining a resource point, we can set the current limit and downgrade policies through Dashboard to protect the resource points. At the same time, can also @SentinelResourceexception handling policies to specify the time limit and downgrade occur. Here, we take a look at each of relegation with current limiting and are to be implemented.

For current limiting control

Step 1: Web layer calls this protected method:


@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/hello")
    public String hello() {
        estService.doSomeThing("hello " + new Date());
        return "didispace.com";
    }

}
复制代码

Step Two: Start the test application, start the Sentinel-Dashboard. Send a request to the /hellointerface, so that several control points can be seen as shown below on the Sentinel-Dashboard:

We can see, in addition to the entry as before there are instances /helloresource points beyond, one more doSomeThingresource points. This point can be provided resources by limiting rule interface, such as 2 to be QPS. Since /helloresources are not set rules limiting, so long as the request /hellointerface, you can call direct analog doSomeThingresources, to observe the limiting rule is in effect.

The following can be invoked by any tool you like /hellothe interface, as long as more than 2 QPS, then there will be the following error is returned, on behalf of limiting the policy to take effect.

At this point, the server console will have a corresponding limiting error log:

2019-06-27 11:30:43.514  INFO 36898 --- [nio-8001-exec-3] c.d.a.sentinel.service.TestService       : aaa
2019-06-27 11:30:43.905 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 cause

com.alibaba.csp.sentinel.slots.block.flow.FlowException: null
复制代码

Limiting achieve exception handling

By default, Sentinel current limit processing control resources is a direct throw an exception, that is, the contents of the log in a posted. In no reasonable business undertaking or docking at the front end of the case may be so, but normal circumstances in order to better service users, will achieve some special treatment after being limiting, we do not want to show a blunt error. Then you only need to do some processing based on the example above, for example:

@Slf4j
@Service
public class TestService {

    @SentinelResource(value = "doSomeThing", blockHandler = "exceptionHandler")
    public void doSomeThing(String str) {
        log.info(str);
    }

    // 限流与阻塞处理
    public void exceptionHandler(String str, BlockException ex) {
        log.error( "blockHandler:" + str, ex);
    }
    
}
复制代码

Mainly do two things:

  • By @SentinelResourceannotation blockHandlerto develop specific handler property
  • Implement the processing functions, the transfer function parameters and parameter passing resources must be the same point, and the last with BlockExceptionabnormal parameter; the same time, the return type must be the same.

If you are familiar Hystrix reader should find this design with HystrixCommand defined fallback is very similar, it is easy to understand.

After completion of the above changes, and then attempts to access the interface (Note limiting rules need to configure), then the front will not return exception information, the backend will print exceptionHandlerthe log output definition. And in the actual application, as long as the business need for caching or limiting the request to do so front-end tips based on this method can be implemented.

Realization blown downgrade

@SentinelResourceIn addition to annotation can be used for current limit control, it'll also achieve a similar fuse with Hystrix downgrade policies. Here's a specific look at how to use it.

The first step: As with the current limit control, use the @SentinelResourcecomment tag resource points, such as:

@Slf4j
@Service
public class TestService {

    @SentinelResource(value = "doSomeThing2")
    public void doSomeThing2(String str) {
        log.info(str);
        throw new RuntimeException("发生异常");
    }

}
复制代码

Here in the TestServicecreation of a new class of methods, and use the @SentinelResourcename the resource doSomeThing2. This method throws an exception, with the follow-up to develop strategies based on downgrade abnormal proportion (similar to Hystrix). Sentinel compared Hystrix richer, and based on the response time and the number of downgrading policy exception.

Step Two: In the Web layer calls this protected method:

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/hello2")
    public String hello2() {
        testService.doSomeThing2("hello2 " + new Date());
        return "didispace.com";
    }

}
复制代码

The third step: start the test application, start the Sentinel-Dashboard. Send a request to the /hello2interface, so that you can see on the Sentinel-Dashboard named doSomeThing2resource point. Then click on the "downgrade" button to set the rules for the downgrade resources. As used herein, the abnormal ratio policy, the ratio is set to 0.5 (i.e.: abnormal rate of 50%), the time window is set to 2 (seconds).

Step Four: Verify fuse degraded, according to the above degradation policy configuration, when the doSomeThing2calling method QPS> = 5, if the ratio exceeds 50% abnormal, then subsequent calls within the two seconds will proceed directly fuse downgrade default thrown directly DegradeExceptionabnormalities, such as:

2019-06-27 17:49: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 cause

com.alibaba.csp.sentinel.slots.block.degrade.DegradeException: null
复制代码

Blown downgrade

Downgrade processing method defined in Sentinel fuse is very simple, and very similar to Hystrix. Just use the @SentinelResourceannotation fallbackattribute to specify a particular method name. There is also need to pay attention to the return pass to participate must be consistent. such as:

@Slf4j
@Service
public class TestService {

    // 熔断与降级处理
    @SentinelResource(value = "doSomeThing2", fallback = "fallbackHandler")
    public void doSomeThing2(String str) {
        log.info(str);
        throw new RuntimeException("发生异常");
    }

    public void fallbackHandler(String str) {
        log.error("fallbackHandler:" + str);
    }
}
复制代码

After completing the transformation of the above, restart the application and set doSomeThing2of resources blown downgraded strategy (percentage of abnormal use), then frequent requests /hello2interface. After QPS> = 5, due this interface has been thrown, it will blow downgraded conditions are met, this time will perform the fallbackHandlermethod, continuous printing log as follows:

2019-06-27 23:44:19.432 ERROR 58471 --- [nio-8001-exec-1] c.d.a.sentinel.service.TestService       : fallbackHandler:hello2 Thu Jun 27 23:44:19 CST 2019
2019-06-27 23:44:19.599 ERROR 58471 --- [nio-8001-exec-2] c.d.a.sentinel.service.TestService       : fallbackHandler:hello2 Thu Jun 27 23:44:19 CST 2019
2019-06-27 23:44:19.791 ERROR 58471 --- [nio-8001-exec-3] c.d.a.sentinel.service.TestService       : fallbackHandler:hello2 Thu Jun 27 23:44:19 CST 2019
2019-06-27 23:44:19.975 ERROR 58471 --- [nio-8001-exec-4] c.d.a.sentinel.service.TestService       : fallbackHandler:hello2 Thu Jun 27 23:44:19 CST 2019
2019-06-27 23:44:20.168 ERROR 58471 --- [nio-8001-exec-5] c.d.a.sentinel.service.TestService       : fallbackHandler:hello2 Thu Jun 27 23:44:20 CST 2019
复制代码

More annotation Property Description

About @SentinelResourcenotes two main uses: current-limiting fuse and control downgrade specific use cases introduced over. In addition, the annotation there are other more sophisticated configuration of such ignore certain unusual configuration, functions, and so default degraded, particularly visible following description:

  • value: Resource name, required items (can not be empty)
  • entryType: Entry type, options (by default EntryType.OUT)
  • blockHandler/ blockHandlerClass: blockHandlerCorrespondence processing BlockExceptionfunction name, options. blockHandler range function needs to be accessed public, the type of return needed to match the original method, and parameters need to match the type of the original method and finally add an additional parameter type BlockException. blockHandler default function and requires the original method in the same class. If you want to use other types of functions, you can specify blockHandlerClassthe class of the corresponding Classobjects, pay attention to the corresponding function is necessary for the static function, it can not be resolved otherwise.
  • fallback: Fallback function name, options for providing fallback processing logic when throwing an exception. fallback function can be (except for all types of exceptions exceptionsToIgnoreexception type which is excluded) for processing. fallback function signature and location requirements:
    • Return Value function return value must be consistent with the original type;
    • The method requires a list of parameters and functions consistent with the original, or may be an additional Throwabletype of abnormality corresponding to the received parameter.
    • The default fallback function and requires the original method in the same class. If you want to use other types of functions, you can specify fallbackClassthe class of the corresponding Classobjects, pay attention to the corresponding function is necessary for the static function, it can not be resolved otherwise.
  • defaultFallback(Since 1.6.0): The default fallback function name, option, typically used for general fallback logic (which can be used for many service or method). The default fallback function can (except for all types of exceptions exceptionsToIgnoreexception types which exclude a) processing. If you configure both fallback and defaultFallback, the only fallback takes effect. defaultFallback function signature requirements:
    • Return Value function return value must be consistent with the original type;
    • The method requires the parameter list is empty, or may be an additional Throwabletype of abnormality corresponding to the received parameter.
    • defaultFallback default function and requires the original method in the same class. If you want to use other types of functions, you can specify fallbackClassthe class of the corresponding Classobjects, pay attention to the corresponding function is necessary for the static function, it can not be resolved otherwise.
  • exceptionsToIgnore(Since 1.6.0): used to specify which exceptions are excluded, not included in the statistical anomaly, and will not enter fallback logic, but as it will be thrown.

Note: prior to version 1.6.0 fallback function only for downgrades very ( DegradeException) is processed, can not deal with exceptions for business .

In particular, if blockHandler and fallback are configured, they were thrown limiting downgrade BlockExceptionwill only enter when blockHandlerprocessing logic. If no configuration blockHandler, fallbackand defaultFallback, will downgrade were limiting BlockException direct throw .

References : Sentinel official documents

Imprint : Based on the spring-cloud-alibaba-dependencies version 0.2.2, if you encounter specific problems, please check the versions are the same, or directly to the check code examples specific cases.

The sample code

This article describes the contents of the client code, readers can view the following examples warehouse alibaba-sentinel-annotationproject:

If you are interested in these, welcomed the star, follow, bookmarking, forwarding support!

Guess you like

Origin juejin.im/post/5d19643ce51d454fbe24a6cc