当前位置:网站首页>Sentinel annotation support - @sentinelresource usage details

Sentinel annotation support - @sentinelresource usage details

2022-06-11 06:18:00 Milo_

Hello, Hello everyone , This is Milo , Let's take you to know about Sentinel in @SentinelResource How to use , This article mainly introduces the following contents to you

Due to the limited level of the author , The article is unavoidably improper , Please give me your advice and suggestions

At present, the official account has no message function , How to find me ? You can pay attention to my official account. : Today, Java, The background to reply " Add group " You can get my personal wechat , At the same time, we can also pull everyone into the exchange group to exchange and learn together

@SentinelResource annotation

Be careful : Annotation embedding is not supported private Method .

Note introduction

@SentinelResource Used to define resources , And provides optional exception handling and fallback Configuration item .

@SentinelResource The annotation contains the following properties :

  • value: Resource name , Required ( Can't be empty )
  • entryTypeentry type , optional ( The default is EntryType.OUT
  • blockHandler / blockHandlerClass: blockHandler Deal with BlockException The function name of , optional .blockHandler The function access range needs to be public, Return type needs to match the original method , The parameter type needs to match the original method and add an extra parameter , The type is BlockException.blockHandler Function default needs to be in the same class as the original method . If you want to use functions of other classes , You can specify blockHandlerClass For the corresponding class Class object , Note that the corresponding function must be static function , Otherwise, it cannot be parsed .
  • fallback/fallbackClassfallback The name of the function , optional , Used to provide... When an exception is thrown fallback Processing logic .fallback Functions can be used for all types of exceptions ( except exceptionsToIgnore The types of exceptions excluded ) To deal with .fallback Function signature and location requirements :
    • The return value type must be the same as the return value type of the original function ;
    • Method parameter list should be consistent with the original function , Or maybe one more Throwable The parameter of type is used to receive the corresponding exception .
    • fallback Function default needs to be in the same class as the original method . If you want to use functions of other classes , You can specify fallbackClass For the corresponding class Class object , Note that the corresponding function must be static function , Otherwise, it cannot be parsed .
  • defaultFallback(since 1.6.0): default fallback The name of the function , optional , Usually used for general purpose fallback Logic ( It can be used in many services or methods ). Default fallback Functions can be used for all types of exceptions ( except exceptionsToIgnore The types of exceptions excluded ) To deal with . If you configure fallback and defaultFallback, only fallback Will take effect .defaultFallback Function signature requirements :
    • The return value type must be the same as the return value type of the original function ;
    • Method parameter list needs to be empty , Or maybe one more Throwable The parameter of type is used to receive the corresponding exception .
    • defaultFallback Function default needs to be in the same class as the original method . If you want to use functions of other classes , You can specify fallbackClass For the corresponding class Class object , Note that the corresponding function must be static function , Otherwise, it cannot be parsed .
  • exceptionsToIgnore(since 1.6.0): Used to specify which exceptions are excluded , It will not be included in the abnormal statistics , And will not enter fallback In the logic , But will throw out as is .

1.8.0 Version start ,defaultFallback Support configuration at the class level .

notes :1.6.0 Previous version fallback Function is only for degraded exceptions (DegradeException) To deal with , Can't handle business exceptions .

Specially , if blockHandler and fallback It's all configured , It is degraded by current limiting and thrown BlockException It will only enter blockHandler Processing logic . If not configured blockHandlerfallback and defaultFallback, When it is degraded by current limiting, it will BlockException Direct selling ( If the method itself is undefined throws BlockException Will be JVM Packaging layer UndeclaredThrowableException).

Annotations use

Code writing

 The code structure

SentinelController

/** *  annotation  @SentinelResource Study  * @author Milo Lee * @date 2021-03-23 11:33 */
@RestController
public class SentinelController {
    

    @Autowired
    private ISentinelService service;

    @GetMapping(value = "/hello/{s}")
    public String apiHello(@PathVariable long s) {
    
        return service.hello(s);
    }
}

ISentinelService

/** * @author Milo Lee * @date 2021-03-23 11:34 */
public interface ISentinelService {
    

    String hello (long s);
}

SentinelServiceImpl

/** * @author Milo Lee * @date 2021-03-23 11:34 */
@Service
@Slf4j
public class SentinelServiceImpl implements ISentinelService {
    


    /** *Sentinel  Provides  @SentinelResource  Annotations are used to define resources  * @param s * @return */
    @Override
    //value: Resource name , Required ( Can't be empty )
    //blockHandler  Deal with  BlockException  The function name of 
    //fallback  Used to provide... When an exception is thrown  fallback  Processing logic 
    @SentinelResource(value = "hello", blockHandler = "exceptionHandler", fallback = "helloFallback")
    public String hello(long s) {
    
        log.error("hello:{}",s);
        return String.format("Hello at %d", s);
    }

    // Fallback  function , The signature of the function is the same as the original function or add one  Throwable  Parameters of type .
    public String helloFallback(long s) {
    
        log.error("helloFallback:{}",s);
        return String.format("Halooooo %d", s);
    }

    // Block  Exception handling functions , One more parameter at the end  BlockException, The rest is consistent with the original function .
    public String exceptionHandler(long s, BlockException ex) {
    
        // Do some log here.
        log.error("exceptionHandler:{}",s);
        ex.printStackTrace();
        return "Oops, error occurred at " + s;
    }
}

Launch our project , Visit our test methods ( Refresh several times , Look at the control panel )

Current limiting test

Now we're looking for our resources :hello Configure a flow control rule , The configuration steps are shown in the figure below

Configuration is successful :

Back to our page , Quickly refresh the page , We will find the following information occasionally , It shows that our configured flow control rules are successfully intercepted

Console log :

According to what we learned above , If it exceeds our configuration QPS, The code will throw BlockException abnormal , Why is it in the code FlowException, By looking at the source code, we will find FlowException It's actually BlockException The children of

After the above test , We found that the successful implementation of annotation development achieved current limiting

Degradation test

Before the downgrade test , We need to modify our code

front :

@SentinelResource(value = "hello", blockHandler = "exceptionHandler", fallback = "helloFallback")

after :

@SentinelResource(value = "hello",  fallback = "helloFallback")

Configure flow control rules

Configure degradation rules :

The test method

According to our configuration rules , If qps>1, I'm sure we'll start BlockException, At this time, the degradation rule judges that the exception ratio exceeds the number of requests 20%, Will automatically trigger a downgrade ;

My click rate : uniform ------ Fast

Look at the logs here , When I started clicking at a constant speed , Did not enter helloFallback Method , When I click quickly , Into the helloFallback Method , It means that the demotion rule will take effect at this time , Trigger downgrade , Enter the callback function helloFallback in ;

Today's sharing is here , Thank you.

原网站

版权声明
本文为[Milo_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020528131307.html