preface

Sentinel is a flow control component for distributed service architecture. It mainly takes traffic as the entry point and helps developers to ensure the stability of microservices from multiple dimensions such as traffic limiting, traffic shaping, circuit breaker degradation, system load protection and hotspot protection. Since Hytrix went into maintenance in 2018 and hytrix was removed in springCloud 2020.0, it can be expected that alibaba Sentinel will be the primary component of springCloud’s whole bucket for some time to come.

Today, let’s talk about some examples of circuit breaker downgrades that failed due to improper use of Alibaba Sentinel. Because Sentinel is still iterating and updating, there will be some differences between different versions, and some problems may have been fixed during the iteration.

The sentinel-Dashboard version demonstrated in this article uses 1.8.0. The version using SpringCloud Alibaba is 2.2.3.release

Failure scenario example

1. The demotation does not take effect

A. Cause analysis

Custom global exception handling is used in the project, and the number or proportion of exceptions is counted in

com.alibaba.csp.sentinel.adapter.spring.webmvc.AbstractSentinelInterceptor.afterCompletion
Copy the code

This method executes before custom global exception handling

com.alibaba.csp.sentinel.adapter.spring.webmvc.AbstractSentinelInterceptor.afterCompletion
Copy the code

This method is executed, because we have to deal with abnormal in exception, converted to an object, for example, that lead to AbstractSentinelInterceptor. AfterCompletion unable to get to the exception, and can’t count count or proportion.

B. Solutions

In the official issue, some netizens have proposed solutions github.com/alibaba/Sen… And github.com/alibaba/Sen…

Because I was looking up the issue before, through the source tracking, find the answer, here I said the realization of the train of thought. The way I think about it is to define a section and do exception statistics on AfterThrowing of the section. Because the aspect is executed before the global exception. I copied the source code of Sentinel statistics directly. The core code is as follows

@Aspect
@Component
@Slf4j
public class StatisticsExceptionCountAspect {

    @Autowired
    @Lazy
    private BaseWebMvcConfig baseWebMvcConfig;

    @Pointcut("execution(* com.github.lybgeek.sentinel.controller.. *. * (..) )"
    public void pointcut(a){}@AfterThrowing(pointcut = "pointcut()",throwing = "ex")
    public void afterAfterThrowing(Throwable ex){
        log.info("statisticsExceptionCount...");
        traceException(ex);
    }

    /** * Abnormal statistics *@param ex
     */
    private void traceException(Throwable ex) {
        Entry entry = getEntryInRequest();
        if(entry ! =null) { Tracer.traceEntry(ex, entry); }}protected Entry getEntryInRequest(a) {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes)requestAttributes;
        HttpServletRequest request = attributes.getRequest();
        Object entryObject = request.getAttribute(baseWebMvcConfig.getRequestAttributeName());
        return entryObject == null ? null: (Entry)entryObject; }}Copy the code

2. Authorization rules do not take effect

A. Cause analysis

Not implemented in the project

com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser
Copy the code

Interface, the source of the request cannot be resolved

B. Solutions

Customize the request source parser in your project. The sample code is as follows

* * *@description: Resolves the access source for authorization rules -- blacklist and whitelist. * When authorization rules are to be performed, RequestOriginParser must be configured, otherwise authorization rules will not take effect ** */@Component
public class CustomRequestOriginParser implements RequestOriginParser {

    @Override
    public String parseOrigin(HttpServletRequest request) {
        String origin = request.getParameter("origin");
        if(! StringUtils.isEmpty(origin)){// Depending on whether the interface carries the origin parameter, if the parameter is origin= PC,
            // If the source of the sentinel-Dashbord authorization rule is set to PC, it means that the source of the request is PC and the blacklist and whitelist configuration is performed

            return origin;
        }
        // If no request parameter is not carried by the interface, it indicates that the blacklist and whitelist is set by IP
        returnrequest.getRemoteAddr(); }}Copy the code

3. The hotspot rule does not take effect

A. Cause analysis

If the url is used as the resource name, the rule does not take effect

B. Solutions

Use the name defined in the @sentinelResource annotation as the resource name

Refer to the official issue github.com/alibaba/Sen…

This may also occur after configuring @SentinelResource

java.lang.reflect.UndeclaredThrowableException: null
Copy the code

Solution: Add the throws BlockException or blockHandler to the method to handle exceptions

Refer to official issue

Github.com/alibaba/Sen…

The sample code

    @GetMapping(value = "/paramFlowRule/{msg}")
    @apiImplIcitParams ({@apiImplIcitParam (name=" MSG ",defaultValue =" hello",value=" message ", paramType =" path"),})
    @apiOperation (value = "Test hotspot rule ")
    @SentinelResource(value = "testParamFlowRule")
    public AjaxResult<String> testParamFlowRule(@PathVariable("msg") String msg) throws BlockException {
        System.out.println(String.format("msg : %s",msg));
        return AjaxResult.success("Test hot spot rules");
    }
Copy the code

conclusion

This article mainly introduces the common problems that may be encountered in the use of Alibaba Sentinel. I cannot say that Ali has done a really good job in open source in China, and most of the questions can be answered in the official issue

The Demo link at the bottom of this article provides other examples of circuit breaker downgrading as well as examples of functionality based on file persistent circuit breaker downgrading configurations. Interested friends can take a look.

The demo link

Github.com/lyb-geek/sp…