Java's SpringCloud Alibaba [5] [Microservice Sentinel integrates openfeign for downgrade]

Insert image description here

1. Sentinel integrates openfeign

1. Copy the order-openfeign project (create order-openfeign-sentinel)

Insert image description here
Insert image description here

Insert image description here
Then write the corresponding interface in stock-nacos
Insert image description here

    @RequestMapping("/reduct2")
    public String reduct2(){
    
    
        int a = 1/0;

        System.out.println("扣减库存");
        return "扣减库存:"+port;
    }

Write the corresponding business logic for calling microservices in order-openfeign-sentinel
Insert image description here

@FeignClient(name = "stock-service",path = "/stock",configuration = FeignConfig.class)
public interface StockFeignService {
    
    
    @RequestMapping("/reduct2")
    public String reduct2();

}

Write the corresponding interface to call the microservice
Insert image description here

@RestController
@RequestMapping("/order")
public class OrderController {
    
    

    @Autowired
    private StockFeignService stockFeignService;

    @RequestMapping("/add")
    public String add(){
    
    
        return stockFeignService.reduct2();
    }
}

Improve the configuration file
Insert image description here
and run the project.
Insert image description here
Insert image description here
Visit: http://localhost:8041/order/add

Insert image description here

2. Sentinel integrates openfeign

Introduce Sentinel dependency

        <!--Sentinel依赖-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

Insert image description here
Insert image description here
Insert image description here

@Component
public class StockFeignServiceFallback implements StockFeignService{
    
    
    @Override
    public String reduct2() {
    
    
        return "降级啦!!";
    }
}

Insert image description here


/*
*
* 2、添加feign接口和方法
* name 指定调用rest接口所对应的服务名
* path 指定调用的rest接口所在的StockController指定的@RequestMapping
* */
@FeignClient(name = "stock-service",path = "/stock",fallback = StockFeignServiceFallback.class)
public interface StockFeignService {
    
    
    @RequestMapping("/reduct2")
    public String reduct2();

}

Configure yml
Insert image description here

feign:
  sentinel:
    # openfeign 整合sentinel
    enabled: true

Insert image description here
Visit: http://localhost:8041/order/add
Insert image description here
Insert image description here

2. Hotspot parameter current limiting [hotspot identification flow control]

What is a hotspot? Hotspots are frequently accessed data.

Many times we want to count the most frequently accessed data in a certain hotspot data and restrict its access.

For example:
Insert image description here
You can limit the current flow of specified parameters passed in on the method.

Hotspot parameter current limiting will count the hotspot parameters in the incoming parameters, and limit the current flow of resource calls containing hotspot parameters based on the configured current limiting threshold and mode.
Hotspot parameter current limiting can be regarded as a special flow control, which only takes effect on resource calls containing hotspot parameters.
Insert image description here

Note:
1. Hotspot rules need to use @SentinelResource("resourceName")annotations, otherwise they will not take effect.
2. Parameters must be 7 basic data types to take effect
. Test cases
Insert image description here

    @RequestMapping("/get/{id}")
    @SentinelResource(value = "getById",blockHandler = "HotBlockHandler")
    public String getById(@PathVariable("id")  Integer id){
    
    
        System.out.println("正常访问");
        return "正常访问";
    }
    public String HotBlockHandler(@PathVariable("id")  Integer id, BlockException e){
    
    
        return "热点异常处理";
    }
}

Perform flow control on the above id parameter.
Visit: http://localhost:8041/order/get/1
Insert image description here
Insert image description here
Insert image description here
Insert image description here

Insert image description here
Insert image description here
Constant access: http://localhost:8041/order/get/1
Insert image description here
We access the one with ID 2.
Constant access: http://localhost:8041/order/get/2
No matter how the access is, it is still normal.
Insert image description here

3. Detailed explanation of Sentinel console rule configuration

1. System rules

Insert image description here
The Sentinel system's adaptive current limiting controls the application inlet flow from the overall dimension. It combines the monitoring indicators of several dimensions such as the application's load, CPU usage, overall average RT, entrance QPS and the number of concurrent threads, and adopts an adaptive flow control strategy. , let the inlet
traffic of the system and the load of the system reach a balance, so that the system can run at the maximum throughput while ensuring the overall stability of the system.

  • Load adaptive (only effective for Linux/Unis-like machines): The system's load1 is used as a heuristic indicator for adaptive system protection.
    System protection (BBR phase) will be triggered only when the system load1 exceeds the set heuristic value and the current number of concurrent threads in the system exceeds the estimated system capacity. System capacity is estimated by the system's maxOps * minRt. The setting reference value is generally CPU cores * 2.5.
    https://www.cnblogs.com/gentlemanhai/p/8484839.html

2. CPU usage (version 1.5.0+): When the system CPU usage exceeds the threshold, system protection is triggered (value range 0.0-1.0), which is relatively sensitive.

Insert image description here

Insert image description here
constant access
Insert image description here

3. Average RT: When the average RT of all inlet traffic on a single machine reaches the threshold, system protection is triggered. The unit is milliseconds.

4. Number of concurrent threads: When the number of concurrent threads for all inlet traffic on a single machine reaches the threshold, system protection is triggered.

2.0x

5. Ingress QPS: When the QPS of all ingress traffic on a single machine reaches the threshold, system protection is triggered.

Insert image description here
Insert image description here
Visit: http://localhost:8041/order/get/1Continuous
Insert image description here
access
Insert image description here

4. Sentinel persistence

1. Sentinel persistence mode

There are three modes for pushing Sentinel rules:
Insert image description here

1.1 Original mode

If no modifications are made, Dashboard's way of pushing rules is to push the rules to the client through the API and update them directly into the memory: the advantage of
Insert image description here
this approach is that it is simple and has no dependencies; the disadvantage is that the rules will disappear when the application is restarted and are only used for Simple test, cannot be used in production environment.

1.2 Pull mode

Data sources in pll mode (such as local files, RDBMS, etc.) are generally writable. When using it, you need to register the data source on the client: register the corresponding read data source to the corresponding RuleManager, and register the write data source to tansport WritableDataSourceRegistry.

1.3 Push mode

In production environments, push mode data sources are generally more commonly used.

For data sources in push mode, such as remote configuration centers (Zookeeper Nocos, Apole, etc.), the push operation should not be performed by the Sentinel client, but should be managed uniformly through the console and pushed directly. The data source is only responsible for obtaining the configuration. The configuration pushed by the center is updated locally.

Therefore, the correct approach to push rules should be 配置中心控制台/Sentiel控制台→配置中心→ Sentinel数据源→Sentinel,

Instead of pushing it to the configuration center through the Sentinel data source. This process is very clear:

1.3.1 Implement push based on Nacos configuration center console
<dependency>
	<groupId>com.alibaba.csp</groupId>
	<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

Configure flow control rules in nacos configuration center

1.3.2 Configure nacos

http://192.168.180.128:8849/nacos/#/configurationManagement?dataId=&group=&appName=&namespace=&pageSize=&pageNo=

Insert image description here

[
    {
    
    
        "resource": "/order/flow",
        "controlBehavior": 0,
        "count": 10.0,
        "grade": 1,
        "limitApp": "default",
        "startegy": 0
    }
]

Insert image description here

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--sentinel启动器-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>
    </dependencies>

Set the corresponding configuration file
Insert image description here

server:
  port: 8861
spring:
  application:
    name: order-sentinel
  cloud:
    sentinel:
      transport:
        dashboard: 127.0.0.1:8858
      web-context-unify: false #默认将调用链路收敛
      datasource:
        flow-rule:
          nacos:
            server-addr: 192.168.180.128:8849
            username: nacos
            password: nacos
            dataId: order-sentinel-flow-rule
            rule-type: flow

Visit: http://127.0.0.1:8861/order/flow
Insert image description here
. Click to visit continuously.
Insert image description here

We can see
http://127.0.0.1:8858/#/dashboard/flow/order-sentinel

sentinel is persisted
Insert image description here

Guess you like

Origin blog.csdn.net/qq_44757034/article/details/132332542