preface

The rules configured on the Sentinel Dashboard management interface are stored in the memory by default. Once Sentinel Dashboard is restarted, the configuration rules disappear and are not applicable to the generation environment.

The source code of Sentinel Dashboard is modified as follows, and the rules are persisted in NACOS based on the Master branch of Sentinel 1.8

Making warehouse address: https://github.com/alibaba/Sentinel.git

1. The Sentinel – Dashboard

1.1 Modifying Dependencies

Modify the pom. XML of the Sentinel-Dashboard module to comment out the test dependent on the Sentinel-datasource-nacos

<! -- for Nacos rule publisher sample --> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-nacos</artifactId> <! --<scope>test</scope>--> </dependency>Copy the code

1.2 Modifying The Java code related to NACOS

Find the following directory

sentinel-dashboard/src/test/java/com/alibaba/csp/sentinel/dashboard/rule/nacos
Copy the code

Copy the entire directory to

sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos
Copy the code

Transform NacosConfig class

  1. Add each rule converter
  2. The ConfigService Bean modifies the addition of nacOS-related connection configurations so that the corresponding configuration items can be specified by JVM parameters at startup
@configuration public class NacosConfig {// Specify the bean name @bean ("flowRuleEntityEncoder") public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() { return JSON::toJSONString; } // Specify bean name @bean ("flowRuleEntityDecoder") public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() { return s -> JSON.parseArray(s, FlowRuleEntity.class); } // // Other EntityEncoder, EntityDecoder.... // E.g. Degrade,param-flow,system,authority, GW-flow, GW-apI-group // // Add the nacOS connection configuration @bean @ConfigurationProperties("spring.cloud.nacos.config") public NacosConfigProperties nacosConfigProperties() { return new NacosConfigProperties(); } @Bean public ConfigService nacosConfigService(NacosConfigProperties configProperties) throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, configProperties.getServerAddr()); properties.put(PropertyKeyConst.NAMESPACE, configProperties.getNamespace()); return ConfigFactory.createConfigService(properties); } public static class NacosConfigProperties{ private String serverAddr; private String namespace; public String getServerAddr() { return serverAddr; } public void setServerAddr(String serverAddr) { this.serverAddr = serverAddr; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; }}}Copy the code

Modify NacosConfigUtil to add Data Id suffixes for various rules stored in Nacos

 public final class NacosConfigUtil {

    public static final String GROUP_ID = "SENTINEL_GROUP";
    
    public static final String AUTHORITY_DATA_ID_POSTFIX = "-authority-rules";
    public static final String DEGRADE_DATA_ID_POSTFIX = "-degrade-rules";
    public static final String FLOW_DATA_ID_POSTFIX = "-flow-rules";
    public static final String GW_API_DATA_ID_POSTFIX = "-gw-api-rules";
    public static final String GW_FLOW_DATA_ID_POSTFIX = "-gw-flow-rules";
    public static final String PARAM_FLOW_DATA_ID_POSTFIX = "-param-flow-rules";
    public static final String SYSTEM_DATA_ID_POSTFIX = "-system-rules";
}
Copy the code

1.3 Adding NacosProvider and NacosPublisher

  • Copy the reference from the test directoryFlowRuleNacosProviderAdd other typesNacosProvider, the followingDegradeRuleNacosProviderAnd otherparam-flow.system.authority.gw-flow.gw-api-groupIs omitted
@Component("degradeRuleNacosProvider") public class DegradeRuleNacosProvider implements DynamicRuleProvider<List<DegradeRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<String, List<DegradeRuleEntity>> converter; @Override public List<DegradeRuleEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(appName + NacosConfigUtil.DEGRADE_DATA_ID_POSTFIX, NacosConfigUtil.GROUP_ID, 3000); if (StringUtil.isEmpty(rules)) { return new ArrayList<>(); } return converter.convert(rules); }}Copy the code
  • Copy the reference from the test directoryFlowRuleNacosPublisherAdd other typesNacosPublisher, the followingDegradeRuleNacosPublisherAnd otherparam-flow.system.authority.gw-flow.gw-api-groupIs omitted
@Component("degradeRuleNacosPublisher") public class DegradeRuleNacosPublisher implements DynamicRulePublisher<List<DegradeRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<List<DegradeRuleEntity>, String> converter; @Override public void publish(String app, List<DegradeRuleEntity> rules) throws Exception { AssertUtil.notEmpty(app, "app name cannot be empty"); if (rules == null) { return; } configService.publishConfig(app + NacosConfigUtil.DEGRADE_DATA_ID_POSTFIX, NacosConfigUtil.GROUP_ID, converter.convert(rules)); }}Copy the code

1.4 Modifying the Controller class

Modified the flow control rule FlowControllerV1, added the NacosPublisher and NacosProvider of flow, and added, deleted, and checked four interfaces

@restController@requestMapping (value = "/v1/flow") Public Class FlowControllerV1 {restController@requestMapping (value = "/v1/flow") // Inject FlowRuleNacosProvider @autoWired Private FlowRuleNacosProvider FlowRuleNacosProvider; // Inject FlowRuleNacosPublisher @autowired private FlowRuleNacosPublisher FlowRuleNacosPublisher; // Push rules to nacos private void publishRules(String app) throws Exception {List<FlowRuleEntity> rules = repository.findAllByApp(app); this.flowRuleNacosPublisher.publish(app, rules); } @GetMapping("/rules") @AuthAction(PrivilegeType.READ_RULE) public Result<List<FlowRuleEntity>> ApiQueryMachineRules (@requestParam String APP, @requestParam String IP, @RequestParam Integer port) {// omit.... Try {/ / / / comment out this line List < FlowRuleEntity > rules. = sentinelApiClient fetchFlowRuleOfMachine (app, IP, port); / / by NacosProvider from nacos rules List < FlowRuleEntity > rules. = flowRuleNacosProvider getRules (app); rules = repository.saveAll(rules); return Result.ofSuccess(rules); } catch (Throwable) {// omit.... } } @PostMapping("/rule") @AuthAction(PrivilegeType.WRITE_RULE) public Result<FlowRuleEntity> ApiAddFlowRule (@requestBody FlowRuleEntity entity) {// omit.... //publishRules(entity.getApp(), entity.getip (), entity.getPort()).get(5000, timeunit.milliseconds); // Resynchronize to nacOS publishRules(entity.getApp()); return Result.ofSuccess(entity); } catch (Throwable t) {// omit.... } } @PutMapping("/save.json") @AuthAction(PrivilegeType.WRITE_RULE) public Result<FlowRuleEntity> apiUpdateFlowRule(Long  id, String app, String limitApp, String resource, Integer grade, Double count, Integer strategy, String refResource, Integer controlBehavior, Integer warmUpPeriodSec, Integer maxQueueingTimeMs) {// omit.... //publishRules(entity.getApp(), entity.getip (), entity.getPort()).get(5000, timeunit.milliseconds); // Resynchronize to nacOS publishRules(entity.getApp()) when updating; return Result.ofSuccess(entity); } catch (Throwable t) {// omit.... } } @DeleteMapping("/delete.json") @AuthAction(PrivilegeType.WRITE_RULE) public Result<Long> apiDeleteFlowRule(Long id) {// omit.... //publishRules(oldEntity.getApp(), oldentity.getip (), oldEntity.getPort()).get(5000, TimeUnit.MILLISECONDS); // Resynchronize to nacOS publishRules(oldEntity.getApp()) when deleting; return Result.ofSuccess(id); } catch (Throwable t) {// omit.... }}}Copy the code

Degrade,param-flow,system,authority, GW-flow, GW-API-group, etc..

2. Business micro-service project

Add POM dependencies

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

Adding project Configuration

Spring: Cloud: sentinel: transport: port: "20051" Dashboard: 192.168.2.x:8080 # # # add Nacos data source configuration flow: Nacos: data source for Nacos server - addr: ${spring. Cloud. Nacos. Config. Server - addr} # Nacos server URL dataId: ${spring.application.name}-flow-rules groupId: SENTINEL_GROUP namespace: C8247bcf-16a1-42da-bc98-0f6f4c7b5ecc data-type: json rule-type: flow authority: nacOS: # ${spring.cloud.nacos.config.server-addr} #NACOS SERVER URL dataId: ${spring.application.name}-authority-rules groupId: DEFAULT_GROUP namespace: c8247bcf-16a1-42da-bc98-0f6f4c7b5ecc data-type: json rule-type: authority degrade: nacos: # in the data source for NACOS server - addr: ${spring. Cloud. NACOS. Config. Server - addr} # NACOS server URL dataId: ${spring.application.name}-degrade-rules groupId: SENTINEL_GROUP namespace: Degrade param-flow: nacos: # degrade param-flow: ${spring.cloud.nacos.config.server-addr} #NACOS SERVER URL dataId: ${spring.application.name}-param-flow-rules groupId: SENTINEL_GROUP namespace: c8247bcf-16a1-42da-bc98-0f6f4c7b5ecc data-type: json rule-type: param-flow system: nacos: # in the data source for NACOS server - addr: ${spring. Cloud. NACOS. Config. Server - addr} # NACOS server URL dataId: ${spring.application.name}-system-rules groupId: SENTINEL_GROUP namespace: c8247bcf-16a1-42da-bc98-0f6f4c7b5ecc data-type: json rule-type: systemCopy the code