使用Gateway网关配合sentinel-dashboard使用nacos同步数据-打docker镜像
-
克隆sentinel-dashboard到本地:https://github.com/alibaba/Sentinel/
-
开始修改代码:
-
修改
pom.xml
中的sentinel-datasource-nacos的依赖,将<scope>test</scope>
注释掉,这样才能在主程序中使用。<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-nacos</artifactId> <!--<scope>test</scope>--> </dependency>
-
展开test->java->com.alibaba.csp.sentinel.dashboard->rule->nacos
复制NacosConfig到src->java->com.alibaba.csp.sentinel.dashboard->config
复制其余3个文件到src->java->com.alibaba.csp.sentinel.dashboard->rule
-
修改NacosConfig 代码
@Value("${spring.cloud.sentinel.datasource.ds.nacos.serverAddr}") private String serverAddr; @Bean public ConfigService nacosConfigService() throws Exception { return ConfigFactory.createConfigService(serverAddr); }
spring.cloud.sentinel.datasource.ds.nacos.serverAddr=172.****:8850 spring.cloud.sentinel.datasource.ds.nacos.dataId=nocov-cloud-gateway-sentinel-flow-rules.properties spring.cloud.sentinel.datasource.ds.nacos.groupId=SENTINEL_GROUP
-
修改FlowRuleNacosProvider代码
@Value("${spring.cloud.sentinel.datasource.ds.nacos.dataId}") private String dataId; @Value("${spring.cloud.sentinel.datasource.ds.nacos.groupId}") private String groupId; @Override public List<FlowRuleEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(dataId, groupId, 3000); if (StringUtil.isEmpty(rules)) { return new ArrayList<>(); } return converter.convert(rules); }
-
修改FlowRuleNacosPublisher代码
@Value("${spring.cloud.sentinel.datasource.ds.nacos.dataId}") private String dataId; @Value("${spring.cloud.sentinel.datasource.ds.nacos.groupId}") private String groupId; @Override public void publish(String app, List<FlowRuleEntity> rules) throws Exception { AssertUtil.notEmpty(app, "app name cannot be empty"); if (rules == null) { return; } configService.publishConfig(dataId, groupId, converter.convert(rules)); }
-
注意:
- 同时Nacos中应该有如下配置:
- 网关配置:
datasource: ds: nacos: server-addr: ${spring.cloud.nacos.discovery.server-addr} data-id: nocov-cloud-gateway-sentinel-flow-rules.properties namespace: group-id: SENTINEL_GROUP data-type: json # 限流 rule-type: flow
-
打开src->java->com.alibaba.csp.sentinel.dashboard->controller->v2->FlowControllerV2
@Qualifier(“flowRuleDefaultProvider”) 改为 @Qualifier(“flowRuleNacosProvider”)
@Qualifier(“flowRuleDefaultPublisher”) 改为 @Qualifier(“flowRuleNacosPublisher”)
-
打开src->webapp->resources->app->scripts->directives->sidebar->sidebar.html
<li ui-sref-active="active" ng-if="entry.isGateway"> <a ui-sref="dashboard.flow({app: entry.app})"> <i class="glyphicon glyphicon-filter"></i> 流控规则 V2</a> </li>
注意:请仔细查看流控规则,只留一个即可。「因为我使用了Gateway 的sentinel 所以使用entry.isGateway」
-
通过sentinel-dashboard项目打开Terminal,输入
mvn clean package
成功打出Jar包,如果报错:缺少其他Jar,请先在缺少的Jar项目名称下install后在运行命令;
-
-
完成之后:
-
发现问题:sentinel使用nacos保存数据时,无法设置数据格式,所以每次在sentinel上修改流控规则后,nacos中的“配置格式”为无,
查看了比较浅的源码:发现无法自定义配置格式。
但总体不影响使用。