Microservice protection 2 (custom exception result + Sentinel rule persistence)

Table of contents

1. Custom abnormal results

1.1. Exception types

 1.2. Custom exception handling

2. Persistence of rules

2.1. Rule management mode

2.1.1. Raw mode

2.1.2. pull mode

2.1.3. push mode

2.2. Realize the push mode


Following  Microservices Securing  article continues to expand


1. Custom abnormal results

By default, when current limiting, downgrading, or authorization interception occurs, an exception will be thrown to the caller. Abnormal results are flow limiting (current limiting). This is not friendly enough, and it is impossible to know whether it is current limiting, downgrading or authorized interception.

1.1. Exception types

And if you want to customize the return result when an exception occurs, you need to implement the BlockExceptionHandler interface:

public interface BlockExceptionHandler {
    /**
     * 处理请求被限流、降级、授权拦截时抛出的异常:BlockException
     */
    void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception;
}

This method has three parameters:

  • HttpServletRequest request:request对象

  • HttpServletResponse response:response对象

  • BlockException e: the exception thrown when intercepted by sentinel

BlockException here contains several different subclasses:

abnormal illustrate
FlowException Current limit exception
ParamFlowException Abnormal hotspot parameter current limit
DegradeException downgrade exception
AuthorityException Authorization rule exception
SystemBlockException System rule exception

 1.2. Custom exception handling

Next, we define a custom exception handling class in springcloud-product:

package com.wqg.product.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String msg = "未知异常";
        int status=429;
        if (e instanceof FlowException) {
            msg = "请求被限流了";
        } else if (e instanceof ParamFlowException) {
            msg = "请求被热点参数限流";
        } else if (e instanceof DegradeException) {
            msg = "请求被降级了";
        } else if (e instanceof AuthorityException) {
            msg = "没有权限访问";
            status = 401;
        }
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(status);
        response.getWriter().println("{\"msg\": " + msg + ", \"status\": " + status + "}");
    }
}

Restart the test, and in different scenarios, different exception messages will be returned .

Access after setting flow control:

 result:

 

2. Persistence of rules

Now, all rules of sentinel are stored in memory, and all rules will be lost after restarting. In a production environment, we must ensure the persistence of these rules to avoid loss

2.1. Rule management mode

Whether the rules can be persisted depends on the rule management mode. Sentinel supports three rule management modes:

  • Original mode: The default mode of Sentinel, the rules are saved in memory, and the service will be lost after restarting the service.

  • pull mode

  • push mode

2.1.1. Raw mode

Original mode: The rules configured in the console are directly pushed to the Sentinel client, which is our application. Then save it in memory, and it will be lost when the service is restarted

 

2.1.2. pull mode

Pull mode: The console pushes the configured rules to the Sentinel client, and the client saves the configured rules in a local file or database. In the future, we will regularly query local files or databases to update local rules.

 

2.1.3. push mode

Push mode: The console pushes configuration rules to a remote configuration center, such as Nacos. The Sentinel client monitors Nacos, obtains push messages of configuration changes, and completes local configuration updates.

 

2.2. Realize the push mode

Persistence of sentinel , we hope this:

  • The current limit configuration can be edited in the sentinel console and synchronized to nacos for persistence

  • The current limit configuration is modified in nacos, and it can also be synchronized to the sentinel console

To realize the above first function, it is necessary to understand the source code of the sentinel console and modify it accordingly.

But someone on GitHub has already modified it and made an enhanced version of the console.

https://github.com/CHENZHENNAME/sentinel-dashboard-nacos

Open the above URL to download locally


 Unzip the above file:

Open pom.xml in the root directory and modify the version of sentinel

 

  • Enter the project root directory, cmd, and execute the command:

  •  mvn clean package
  • After packaging, it is produced in the target directory

Execute the command to start the console:

java -Dserver.port=8080 -Dnacos.serverAddr=localhost:8848  -jar sentinel-dashboard.jar

 # -Dserver.port console port number
# -Dnacos.serverAddr: nacos address
# -Dnacos.namespace: the nacos namespace where your project is located If the namespace is public, this parameter can be omitted


Open the sentinel interface

 Microservice client access sentinel control panel

In the springcloud-product microservice project

(1) Introduce dependencies

  <!--sentinel配置规则的数据源-->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
            <version>1.8.1</version>
        </dependency>

(2) Modify the configuration file

#sentinel的服务端的地址
spring.cloud.sentinel.transport.dashboard=localhost:8080
spring.cloud.sentinel.datasource.ds1-flow.nacos.server-addr=localhost:8848
spring.cloud.sentinel.datasource.ds1-flow.nacos.data-id=${spring.application.name}-flow-rules
#还可以是degrade authority param-flow
spring.cloud.sentinel.datasource.ds1-flow.nacos.rule-type=flow
spring.cloud.sentinel.datasource.ds1-flow.nacos.data-type=json
spring.cloud.sentinel.datasource.ds1-flow.nacos..group-id=SENTINEL_GROUP

Start the microservice  

Then the browser visits: http://localhost:8080 , there is nothing at first, and then visit any interface of your own project that needs to be limited, and the corresponding service name will appear on the left

Click on the cluster point link to add a flow control rule:

 Note that you must click the one with 2. Only the one with 2 can be pushed to nacos, and it is not possible to add it in the flow control rule option. You can only push it to nacos by clicking the blue box

${application-name}-flow-rulesAfter the addition is successful, in nacos, a configuration file in the format will be automatically generated under the namespace you specified

  When you are in the sentinel console, whether you add or modify rules, it will be synchronized to nacos; on the contrary, modifying the current limiting rules of the configuration file in nacos will also be synchronized to sentinel.

 

Guess you like

Origin blog.csdn.net/WQGuang/article/details/131829627