Sentinel configuration rules persist to Nacos

The nacos version 1.4.2 and sentinel version 1.8.3 used in this article

question

When the client application integrated with Sentinel restarts, all the rules configured in the console are gone. If you need to go to the production environment, you need to persist the rule configuration. Let's implement Sentinel rule configuration persistence.

Add Maven dependency

If you need to persist to nacos, you need to add relevant Maven dependencies

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

<!-- Sentinel Datasource Nacos 依赖 -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

configure

The default dataId and groupId conventions for Nacos adaptation are as follows:

  • groupId: SENTINEL_GROUP
  • Rule configuration dataId: {appName}-flow-rules, for example, if the application name is appA, the dataId is appA-flow-rules
spring:
	cloud:
		sentinel:
			datasource:
			  # 自定义命名
			  flow-rule:
			    # 支持多种持久化数据源:file、nacos、zk、apollo、redis、consul
			    nacos:
			      # naco服务地址
			      server-addr: localhost:8848
			      # 命名空间,根据环境配置
			      namespace: public
			      # 这里我做了一下细分,不同规则设置不同groupId
			      group-id: SENTINEL_FLOW_GROUP
			      # 仅支持JSON和XML类型
			      data-id: ${spring.application.name}-flow-rules.json
			      # 规则类型:flow、degrade、param-flow、system、authority
			      rule-type: flow
			      # nacos开启了认证需要配置username、password
			      # username: nacos
			      # password: nacos
			      

Nacos configuration

insert image description here

[{
	"clusterMode": false,
	"controlBehavior": 0,
	"count": 5.0,
	"grade": 1,
	"limitApp": "default",
	"resource": "/sentinel/flow",
	"strategy": 0
}]

Detailed official documentation for rule configuration: https://sentinelguard.io/zh-cn/docs/basic-api-resource-rule.html

After the configuration is complete, restart the project to see that the rule configuration still exists. Modifying the configuration in Nacos can also be synchronized to the Sentinel console in real time.
insert image description here

The rules added by Sentinel console are pushed to Nacos

From the above, it seems that the configured rules can be persisted, and the rules modified by the Nacos configuration center may be synchronized to the Sentinel console in real time. However, adding, modifying and deleting rules in the console cannot be synchronized to the Nacos configuration center. Added a rule to the console that will be lost if the client restarts. Let's implement the console to add rules and push them to Nacos.

According to the official documentation: Sentinel console provides DynamicRulePublisher and DynamicRuleProvider interfaces for implementing rule push and pull of application dimensions.

Add Maven dependency

<!-- 添加Nacos配置中心依赖 -->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>0.2.10</version>
</dependency>

Add application.properties configuration

groupId is custom named according to naming constraints.

# 配置nacos服务地址与命名空间,可根据环境配置命名空间
nacos.config.server-addr=localhost:8848
nacos.config.namespace=8b1673aa-38da-48c6-bc5a-6df956ed0956

# 配置nacos groupId,可以自定义groupId
# 跟上面一样按照不同规则设置不同groupId
sentinel.nacos.flow.group-id=SENTINEL_FLOW_GROUP
sentinel.nacos.degrade.group-id=SENTINEL_DEGRADE_GROUP
sentinel.nacos.auth.group-id=SENTINEL_AUTH_GROUP
sentinel.nacos.param.group-id=SENTINEL_PARAM_GROUP
sentinel.nacos.system.group-id=SENTINEL_SYSTEM_GROUP

Customize FlowRulePublisher push and implement DynamicRulePublisher interface

/**
 * @ClassName FlowRulePublisher
 * @Description 推送流控规则
 * @Author tigerkin
 * @Date 2022/3/9 14:40
 */
@Component
public class FlowRulePublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {

    private static final Logger LOG = LoggerFactory.getLogger(FlowRulePublisher.class);

    @Value("${sentinel.nacos.flow.group-id}")
    private String nacosFlowGroupId;

    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    /**
     * 重要属性:
     * resource	        资源名,资源名是限流规则的作用对象
     * count	        限流阈值
     * grade	        限流阈值类型,QPS 或线程数模式	                                 QPS 模式
     * limitApp	        流控针对的调用来源	                                             default,代表不区分调用来源
     * strategy	        调用关系限流策略:直接、链路、关联	                             根据资源本身(直接)
     * controlBehavior	流控效果(直接拒绝 / 排队等待 / 慢启动模式),不支持按调用关系限流	 直接拒绝
     * @param app app name
     * @param rules list of rules to push
     * @throws Exception
     */
    @Override
    public void publish(String app, List<FlowRuleEntity> rules) throws Exception {
        if (StringUtil.isBlank(app)) {
            return;
        }
        if (rules == null) {
            return;
        }

        LOG.info("========> 流控规则推送 -> app: {} rules:{}", app, JSON.toJSONString(rules));

        List<FlowRuleEntity> flowFules = rules.stream().map(data -> {
            FlowRuleEntity entity = new FlowRuleEntity();
            entity.setResource(data.getResource());
            entity.setCount(data.getCount());
            entity.setGrade(data.getGrade());
            entity.setLimitApp(data.getLimitApp());
            entity.setStrategy(data.getStrategy());
            entity.setControlBehavior(data.getControlBehavior());
            return entity;
        }).collect(Collectors.toList());

        /**
         * sentinel推送nacos命名约束
         * 流控规则 dataId: {appName}-flow-rules,比如应用名为 appA,则 dataId 为 appA-flow-rules
         */
        String dataId = String.format("%s-flow-rules.json", app);

        HttpHandler.handler(flowFules, nacosConfigProperties, nacosFlowGroupId, dataId);
    }
}

HttpHandler class

/**
 * @ClassName HttpHandler
 * @Description
 * @Author tigerkin
 * @Date 2022/3/10 11:06
 */
public class HttpHandler {

    private static final Logger LOG = LoggerFactory.getLogger(HttpHandler.class);

    public static void handler(Object rules, NacosConfigProperties nacosConfigProperties, String groupId, String dataId) throws IOException {
        StringJoiner param = new StringJoiner("&");
        param.add(String.format("tenant=%s", nacosConfigProperties.getNamespace())); // Nacos 的命名空间ID字段
        param.add(String.format("dataId=%s", dataId));
        param.add(String.format("group=%s", groupId));
        param.add(String.format("content=%s", URLEncoder.encode(JSON.toJSONString(rules), "UTF-8")));
        param.add(String.format("type=%s", "json"));

        String url = String.format("http://%s/nacos/v1/cs/configs?%s", nacosConfigProperties.getServerAddr(), param.toString());
        HttpPost httpPost = new HttpPost(url);

        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse response = httpclient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            LOG.info("========> 发布成功:{}", result);
        } else {
            LOG.error("========> 发布失败:{}", response.toString());
        }
    }
}

After implementing the push interface, find the Controller configured by the Sentinel rules, and add the push logic. What I am transforming here is FlowControllerV1.

Add dependency injection properties:
insert image description here
Finally, find the publisherRules method in the Controller and add the push method call.

Sentinel will send a request to the client to synchronize the rule configuration after the rule is changed.

insert image description here
Add the rules in the console below, and they will be pushed to the Nacos configuration center. So far, the Sentinel configuration rules are persisted to Nacos.
insert image description here
insert image description here
Reference:
Nacos Open API documentation: https://nacos.io/zh-cn/docs/open-api.html
Sentinel github address: https://github.com/alibaba/Sentinel/releases
Sentinel official documentation:
https:/ /github.com/alibaba/Sentinel/wiki/Use in production environment-Sentinel
https://github.com/alibaba/Sentinel/wiki/Sentinel-console (cluster flow control management)#rule configuration

Provide relevant business logic processing source code location, interested children's shoes can take a look.

The source location where the client handles Sentinel requests:

jar: sentinel-transport-common-1.8.3.jar
package: com.alibaba.csp.sentinel.command.handler

insert image description here
nacos monitor processing source code location:

jar: sentinel-datasource-nacos-1.8.3.jar
package: com.alibaba.csp.sentinel.datasource.nacos

insert image description here

Guess you like

Origin blog.csdn.net/weixin_42270645/article/details/123399569