sentinel rule persistence-rule synchronization nacos-the most standard configuration

Official reference document:

Dynamic rule expansion · alibaba/Sentinel Wiki · GitHub

The code that needs to be modified is as follows:

In order to facilitate the integration of nacos in subsequent versions, let’s briefly talk about the integration ideas.

1.Change pom

Modify the scope of sentinel-datasource-nacos

Will

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

Change to

 <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
            <!--<scope>test</scope>-->
</dependency>

2.Copy the example

Copy the contents of the com.alibaba.csp.sentinel.dashboard.rule.nacos package in the test directory to the com.alibaba.csp.sentinel.dashboard.rule directory in src

The test directory only contains current limiting, other rules can be created by reference.

Pay attention to modifying constants when creating, and implement various converters in NacosConfig

Note: Authorization rules and hotspot rules require special processing, otherwise the nacos configuration will not take effect.

Because the authorization rule Entity contains one more layer than the flow control rule Entity.

public class FlowRuleEntity implements RuleEntity
public class AuthorityRuleEntity extends AbstractRuleEntity<AuthorityRule>

Take authorization rules as an example

AuthorityRuleNacosProvider.java

/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.nacos.authority;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Eric Zhao
 * @since 1.4.0
 */
@Component("authorityRuleNacosProvider")
public class AuthorityRuleNacosProvider implements DynamicRuleProvider<List<AuthorityRuleEntity>> {

    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<String, List<AuthorityRuleEntity>> converter;

    @Override
    public List<AuthorityRuleEntity> getRules(String appName) throws Exception {
        String rules = configService.getConfig(appName + NacosConfigUtil.AUTHORITY_DATA_ID_POSTFIX,
                NacosConfigUtil.GROUP_ID, 3000);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return converter.convert(this.parseRules(rules));
    }

    private String parseRules(String rules) {
        JSONArray newRuleJsons = new JSONArray();
        JSONArray ruleJsons = JSONArray.parseArray(rules);
        for (int i = 0; i < ruleJsons.size(); i + + ) {
            JSONObject ruleJson = ruleJsons.getJSONObject(i);
            AuthorityRuleEntity ruleEntity = JSON.parseObject(ruleJson.toJSONString(), AuthorityRuleEntity.class);
            JSONObject newRuleJson = JSON.parseObject(JSON.toJSONString(ruleEntity));
            AuthorityRule rule = JSON.parseObject(ruleJson.toJSONString(), AuthorityRule.class);
            newRuleJson.put("rule", rule);
            newRuleJsons.add(newRuleJson);
        }
        return newRuleJsons.toJSONString();
    }
}

AuthorityRuleNacosPublisher.java

/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.nacos.authority;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Eric Zhao
 * @since 1.4.0
 */
@Component("authorityRuleNacosPublisher")
public class AuthorityRuleNacosPublisher implements DynamicRulePublisher<List<AuthorityRuleEntity>> {

    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<List<AuthorityRuleEntity>, String> converter;

    @Override
    public void publish(String app, List<AuthorityRuleEntity> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        configService.publishConfig(app + NacosConfigUtil.AUTHORITY_DATA_ID_POSTFIX,
            NacosConfigUtil.GROUP_ID, this.parseRules(converter.convert(rules)));
    }

    private String parseRules(String rules) {
        JSONArray oldRuleJsons = JSONArray.parseArray(rules);
        for (int i = 0; i < oldRuleJsons.size(); i + + ) {
            JSONObject oldRuleJson = oldRuleJsons.getJSONObject(i);
            JSONObject ruleJson = oldRuleJson.getJSONObject("rule");
            oldRuleJson.putAll(ruleJson);
            oldRuleJson.remove("rule");
        }
        return oldRuleJsons.toJSONString();
    }
}

Hotspot rules are the same

3. Modify controller

FlowControllerV2 in v2 directory

Will

 @Autowired
    @Qualifier("flowRuleDefaultProvider")
    private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
    @Autowired
    @Qualifier("flowRuleDefaultPublisher")
    private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;

Change to

 @Autowired
    @Qualifier("flowRuleNacosProvider")
    private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
    @Autowired
    @Qualifier("flowRuleNacosPublisher")
    private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;

Other controllers in the controller directory include

AuthorityRuleController DegradeController FlowControllerV1 ParamFlowRuleController SystemController

Make the following changes (take DegradeController as an example)

Will

@Autowired
    private SentinelApiClient sentinelApiClient;

Change to

@Autowired
    @Qualifier("degradeRuleNacosProvider")
    private DynamicRuleProvider<List<DegradeRuleEntity>> ruleProvider;
    @Autowired
    @Qualifier("degradeRuleNacosPublisher")
    private DynamicRulePublisher<List<DegradeRuleEntity>> rulePublisher;

Delete the original publishRules method and change it to

 private void publishRules(/*@NonNull*/ String app) throws Exception {
        List<DegradeRuleEntity> rules = repository.findAllByApp(app);
        rulePublisher.publish(app, rules);
    }

Then you can resolve the error reported.

Where to get all rules

Will

 List<DegradeRuleEntity> rules = sentinelApiClient.fetchDegradeRuleOfMachine(app, ip, port);

Change to

List<DegradeRuleEntity> rules = ruleProvider.getRules(app);

Delete the original place where publishRules method is called.

Add in the previous try catch method

publishRules(entity.getApp());

The entity.getApp() here may also be variables such as oldEntity.getApp()/app. Just guess based on the deleted publishRules code snippet.

4. Modify front-end files

File path: src/main/webapp/resources/app/scripts/directives/sidebar/sidebar.html

Will

 <a ui-sref="dashboard.flowV1({app: entry.app})">

Change to

 <a ui-sref="dashboard.flow({app: entry.app})">

5. Finally pack it

Execute the command and package it into jar

mvn clean package

The running method is consistent with the official jar and will not be described in detail.

6.Microservice program integration

pom.xml added

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

Configuration file application.yml added

spring:
  cloud:
    sentinel:
      datasource:
        # The name is arbitrary
        flow:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-flow-rules
            groupId: SENTINEL_GROUP
            # Rule type, see value:
            # org.springframework.cloud.alibaba.sentinel.datasource.RuleType
            rule-type: flow
        degrade:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-degrade-rules
            groupId: SENTINEL_GROUP
            rule-type: degrade
        system:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-system-rules
            groupId: SENTINEL_GROUP
            rule-type: system
        authority: authority
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-authority-rules
            groupId: SENTINEL_GROUP
            rule-type: authority
        param-flow:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-param-flow-rules
            groupId: SENTINEL_GROUP
            rule-type: param-flow

7. Test verification

After adding several flow control rules in the sentinel console interface, try closing the microservice and sentinel, and then reopen sentinel and the microservice to see if the flow control rules are still there.

8. Finally, the configured code will be sent to everyone. You can download it by yourself. It contains the running access process.

https://download.csdn.net/download/qq_34091529/88482757