@SentinelResource annotation details

stay SpringCloudAlibaba-Sentinel In this document, we have introduced the general knowledge of Sentinel.
However, the @ SentinelResource annotation did not mention its details in that document, that is, it was simply mentioned.
The annotation of that document is introduced at: https://www.yuque.com/shmily-kbnvv/xxbj/ci2gs5#9lIy9 //todo to be modified to csdn address

Let's make a detailed introduction here. Firstly, this annotation is similar to the @ HystrixCommand annotation in Hystrix, indicating that the Sentinel resource definition is an annotation defined on the method.

By viewing the source code, we can see that the annotation has so many attributes:

Then we explain it one by one.

  • Value: the name of Sentinel resource. We can not only limit the flow through the url, but also configure this value as the resource name, which can also limit the flow.
  • entryType: entry type (inbound or outbound). The default is outbound (EntryType.OUT)
  • resourceType: Resource Classification (type)
  • blockHandler: the name of the block exception function, which is empty by default
  • blockHandlerClass: Specifies the class where the block processing method is located
    • By default, blockHandler is in the same class as the original method. However, if some methods share the same signature and intend to set the same block handler, you can set the class where the block handler exists. Note that block handler methods must be static.
  • fallback: the name of the backup function. It is empty by default
  • defaultFallback: the name of the default fallback method. It is empty by default
    • defaultFallback is used as the default generic fallback method. It should not accept any parameters and the return type should be compatible with the original method
  • fallbackClass: the class where the fallback method is located (only a single class)
    • By default, fallback is in the same class as the original method. However, if some methods share the same signature and intend to set the same fallback, the user can set the class with fallback function. Note that the shared fallback method must be static.
  • exceptionsToTrace: List tracing of exception classes. Throwable by default
  • exceptionsToIgnore: the list of exception classes to ignore. It is empty by default

Then we will introduce them in detail one by one:

value

    /**
     * @return name of the Sentinel resource
     */
    String value() default "";

We can define the resource name corresponding to this method through the value value of @ SentinelResource annotation.
for instance:

        //The two methods are the same, but when configuring multiple parameters, you must bring the attribute name value.
        @SentinelResource("helloSentinelResource")
        // @SentinelResource(value = "helloSentinelResource")
        public String helloSentinelResource(){
            return "helloSentinelResource";
        }

So what's the use of this annotation and configuring this property?
The value value of this annotation specifies the name of this api resource configured by us, which can be used in our current limiting and fusing configurations (the url configured by @ RequestMapping can also be used in current limiting and fusing configurations).
Here is an example of current limiting:
An interface is defined:

        @RequestMapping("/helloRequestMapping")
        @SentinelResource("helloSentinelResource")
        public String sentinelResource(){
            return "sentinelResource";
        }

Configure in Sentinel console:
First, use the value of @ RequestMapping to configure and save.
If you access this interface twice in a row (within one second), you will find that the interface is current limited.

Then use the value of @ SentinelResource to configure and save (remember to delete the content just configured).
If you access this interface twice in a row (within one second), you will find that the interface is current limited (although the display content is different, it is true that it is current limited).

entryType

The flow type of resource call, whether it is inlet flow or outlet flow.

    /**
     * @return the entry type (inbound or outbound), outbound by default
     */
    EntryType entryType() default EntryType.OUT;

To verify, add the following two interfaces and configure the system inlet flow restriction rules:

        @RequestMapping("/out")
        @SentinelResource(value = "entryTypeOut",entryType = EntryType.OUT)
        public String entryTypeOut() throws InterruptedException {
            return "sentinelResource";
        }

        @RequestMapping("/in")
        @SentinelResource(value = "entryTypeIn",entryType = EntryType.IN)
        public String entryTypeIn() throws InterruptedException {
            return "sentinelResource";
        }


Then access each interface twice a second. We can find that entrytype = entrytype The interface of out is not current limited, entrytype = entrytype The interface of in is current limited.

resourceType

Classification (type) of resources
It is used to identify the classification of resources, 0-general, 1-WEB, 2-RPC, 3-GATEWAY and 4-SQL, which are defined in ResourceTypeConstants class.

I didn't find out what this number corresponds to through official documents, source code, annotations, etc. I asked others to know. If anyone sees where a confidant can find this class, let me know.

    /**
     * @return the classification (type) of the resource
     * @since 1.7.0
     */
    int resourceType() default 0;

In Sentinel's real-time monitoring, one field is resource classification, which can be used as a condition.
reference resources: https://github.com/alibaba/Sentinel/wiki/ Second level log of real-time monitoring # resources

blockHandler

The name of the block exception function, which is empty by default.
blockHandler corresponds to the name of the method handling BlockException. Optional.
Normally, if we reach the current limit threshold and are blown, we will return the 500 error page. If we configure the blockHandler property, it will execute a method named the value of this property.

    /**
     * @return name of the block exception function, empty by default
     */
    String blockHandler() default "";

There are several requirements for configuring the method as the value of this attribute:

  • Method name: defined casually
  • Scope: public
  • Parameter: on the basis of consistency with the original method, add a parameter of type BlockException on the last side.
  • The return type should be consistent with the original method.
  • Static?: If blockHandlerClass is used to specify methods in other classes, this method must be static, otherwise it cannot be resolved.

Test:
Write two methods, one for us to access and the other for us to access after an access error (current limiting and fusing), and configure the current limiting on the console.

        @RequestMapping("/blockHandler")
        @SentinelResource(value = "blockHandler", blockHandler = "blockHandlerErr")
        public String blockHandler() {
            return "blockHandler O(∩_∩)O";
        }

        public String blockHandlerErr(BlockException be) {
            return "blockHandler ┭┮﹏┭┮";
        }


Since the configured current limit threshold is 1, the return content of the blockHandler method is displayed when accessed once a second, and the return content of the blockHandlerErr method is displayed when accessed more than twice.

blockHandlerClass

Specifies the class of the block processing method
The fallback method needs to be in the same class as the original method by default. If the value of blockHandlerClass attribute is specified, the method in the specified class is used.
If it is a method in another class, the method must be static.

    /**
     * The {@code blockHandler} is located in the same class with the original method by default.
     * However, if some methods share the same signature and intend to set the same block handler,
     * then users can set the class where the block handler exists. Note that the block handler method
     * must be static.
     *
     * @return the class where the block handler exists, should not provide more than one classes
     */
    Class<?>[] blockHandlerClass() default {};

Test:
Use the blockHandlerClass parameter to specify which method in the class needs to be used. Note that the methods in the specified class must be static, Whether it's other classes or this class (of course, the methods in this class don't need this parameter. They default to this class directly, and they don't need to be static. If this class is specified, you also need to change the specified method to static. It's unnecessary to kill one stone and look for trouble if you have nothing to do).
Then conduct current limiting control and set the threshold to 1. It is normal when accessed once a second, and the methods in the specified class will be called when accessed twice.

fallback

The name of the backup function. It is empty by default and optional.
It is used to provide fallback processing logic when throwing exceptions. The fallback method can handle all types of exceptions (except those excluded in the exceptionsToIgnore parameter).
It uses the same method as blockHandler, but handles different exceptions.
If blockHandler is configured, the method specified by blockHandler will be executed when current limiting and fusing, and the method specified by fallback will be executed for other exceptions. If not configured, execute the method configured in fallback.

    /**
     * @return name of the fallback function, empty by default
     */
    String fallback() default "";

Test:

  1. Both fallback and blockHandler are configured

If blockHandler is configured, the method specified by blockHandler will be executed when current limiting and fusing, and the method specified by fallback will be executed for other exceptions.

    public String blockHandlerErr(BlockException be) {
        return "blockHandler ┭┮﹏┭┮";
    }

    @RequestMapping("/fallback")
    @SentinelResource(value = "fallback", fallback = "fallbackErr", blockHandler = "blockHandlerErr")
    public String fallback() {
        int i = 1 / 0;
        return "fallback O(∩_∩)O";
    }

    public String fallbackErr() {
        return "fallback ┭┮﹏┭┮";
    }

  1. Configure fallback only

If blockHandler is not configured, the method configured in fallback will also be executed when current limiting and fusing.

    public String blockHandlerErr(BlockException be) {
        return "blockHandler ┭┮﹏┭┮";
    }

    @RequestMapping("/fallback")
    @SentinelResource(value = "fallback", fallback = "fallbackErr")
    public String fallback() {
        int i = 1 / 0;
        return "fallback O(∩_∩)O";
    }

    public String fallbackErr() {
        return "fallback ┭┮﹏┭┮";
    }


defaultFallback

If the value of fallback is not configured, it will come here by default. Default fallback method name, optional, usually used for general fallback logic. The default fallback method can handle all types of exceptions (except those excluded in exceptionsToIgnore). If both fallback and defaultFallback are configured, only fallback will take effect.

Test:

  1. Both the fallback parameter and the defaultFallback parameter are configured:
    @RequestMapping("/fallback")
    @SentinelResource(value = "fallback", fallback = "fallbackErr",defaultFallback = "defaultFallbackErr")
    public String fallback() {
        int i = 1 / 0;
        return "fallback O(∩_∩)O";
    }

    public String fallbackErr() {
        return "fallback ┭┮﹏┭┮";
    }
    public String defaultFallbackErr() {
        return "defaultFallback ┭┮﹏┭┮";
    }


  1. Only the defaultFallback parameter is configured:
    @RequestMapping("/fallback")
    @SentinelResource(value = "fallback", defaultFallback = "defaultFallbackErr")
    public String fallback() {
        int i = 1 / 0;
        return "fallback O(∩_∩)O";
    }

    public String fallbackErr() {
        return "fallback ┭┮﹏┭┮";
    }

    public String defaultFallbackErr() {
        return "defaultFallback ┭┮﹏┭┮";
    }


fallbackClass

Specifies the class of the block processing method
The fallback method needs to be in the same class as the original method by default. If the value of blockHandlerClass attribute is specified, the method in the specified class is used.
If it is a method in another class, the method must be static.

    /**
     * The {@code fallback} is located in the same class with the original method by default.
     * However, if some methods share the same signature and intend to set the same fallback,
     * then users can set the class where the fallback function exists. Note that the shared fallback method
     * must be static.
     *
     * @return the class where the fallback method is located (only single class)
     * @since 1.6.0
     */
    Class<?>[] fallbackClass() default {};

The process of using handlerclass is almost different from the actual test.

exceptionsToTrace

Used to specify which exceptions are counted, as opposed to exceptionsToIgnore. Optional. The default is Throwable.
It is generally used with fallback.

    /**
     * @return the list of exception classes to trace, {@link Throwable} by default
     * @since 1.5.1
     */
    Class<? extends Throwable>[] exceptionsToTrace() default {Throwable.class};

Test:
Write two methods, an interface method and a fallback specifying method.
In the interface method, the ArrayIndexOutOfBoundsException exception is thrown when the parameter num=1 is passed in, and the NumberFormatException exception is thrown when the parameter num=2 is passed in.
Through the control of exceptionsToTrace and fallback, only the ArrayIndexOutOfBoundsException exception is counted. When the ArrayIndexOutOfBoundsException exception occurs, the exceptionsToTraceFallbackErr method is called (other exceptions are not handled).

    @RequestMapping("/exceptionsToTrace")
    @SentinelResource(value = "exceptionsToTrace",
            exceptionsToTrace = ArrayIndexOutOfBoundsException.class,
            fallback = "exceptionsToTraceFallbackErr")
    public String exceptionsToTrace(int num) {
        if (num == 1) {
            int[] ints = {1, 2, 3};
            System.out.println(ints[10]);
        } else {
            int i = Integer.valueOf("s");
        }
        return "exceptionsToTrace O(∩_∩)O";
    }

    public String exceptionsToTraceFallbackErr(int num) {
        return "exceptionsToTraceFallbackErr ┭┮﹏┭┮";
    }


exceptionsToIgnore

Used to specify which exceptions are ignored, as opposed to exceptionsToTrace. Optional. Empty by default.
It is generally used with fallback.

    /**
     * Indicates the exceptions to be ignored. Note that {@code exceptionsToTrace} should
     * not appear with {@code exceptionsToIgnore} at the same time, or {@code exceptionsToIgnore}
     * will be of higher precedence.
     *
     * @return the list of exception classes to ignore, empty by default
     * @since 1.6.0
     */
    Class<? extends Throwable>[] exceptionsToIgnore() default {};

Test:
Write two methods, an interface method and a fallback specifying method.
In the interface method, the ArrayIndexOutOfBoundsException exception is thrown when the parameter num=1 is passed in, and the NumberFormatException exception is thrown when the parameter num=2 is passed in.
Through the control of exceptionsToIgnore and fallback, the ArrayIndexOutOfBoundsException exception is not counted. When the ArrayIndexOutOfBoundsException exception occurs, the exceptionsToIgnoreFallbackErr method is called (other exceptions are not handled).

    @RequestMapping("/exceptionsToIgnore")
    @SentinelResource(value = "exceptionsToIgnore",
            exceptionsToTrace = ArrayIndexOutOfBoundsException.class,
            fallback = "exceptionsToIgnoreFallbackErr")
    public String exceptionsToIgnore(int num) {
        if (num == 1) {
            int[] ints = {1, 2, 3};
            System.out.println(ints[10]);
        } else {
            int i = Integer.valueOf("s");
        }
        return "exceptionsToIgnore O(∩_∩)O";
    }

    public String exceptionsToIgnoreFallbackErr(int num) {
        return "exceptionsToIgnoreFallbackErr ┭┮﹏┭┮";
    }


Related content

An additional class SentinelResourceAspect is mentioned, which is how this annotation is implemented.
If you want to see how @ SentinelResource works, just look at the source code of this class.
Full path: com alibaba. csp. sentinel. annotation. aspectj. SentinelResourceAspect. java


Relevant code download address: https://download.csdn.net/download/wangguohui0726/16698689










Keywords: Java Spring Spring Cloud

Added by p.utsav on Fri, 04 Mar 2022 18:56:17 +0200