Sentinel current limiting circuit breaker of microservices (2) — URL resource cleaning

The current limit of the HTTP service in Sentinel is implemented by the CommonFilter in the Sentinel-Web-Servlet package by default. As you can see from the code, this Filter will treat each different URL as a different resource.
In the following code, a REST style API with {id} parameters is provided. For each different {id}, the URL is different, so by default Sentinel will treat all URLs as resources. Flow Control.

package com.yuntai.gateway.config;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UrlCleanController {
    
    @GetMapping("/clean/{id}")
    public String clean(int id){
        return "Hello Clean";
    }
}

This will cause two problems:
1. The current limit statistics are not accurate. The actual demand is to control the total QPS of the clean method, and the result is the QPS of each URL;
2. The number of resources in Sentinel is too much, and the default threshold of the number of resources It is 6000, and the rules for extra resources will not take effect.

To solve this problem, you can implement resource cleaning through the UrlCleaner interface, that is, for the URL /clean/{id}, we can collectively group it under the /clean/* resource. The specific configuration code is as follows to implement the UrlCleaner interface and rewrite clean Method.

package xxx;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.UrlCleaner;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
public class CustomUrlCleaner implements UrlCleaner {
    @Override
    public String clean(String originUrl) {
        if(StringUtils.isBlank(originUrl)){
            return originUrl;
        }
        if(originUrl.startsWith("/clean/")){
            return "/clean/*";
        }
        return originUrl;
    }
}

Excerpted from the book "Spring Cloud Alibaba Microservice Principles and Practices" by Bubble Academy

Guess you like

Origin blog.csdn.net/weixin_39195030/article/details/112726455