Sentinel规则持久化到Nacos教程

环境:

1、sentinel版本:1.8.6,下载地址:https://github.com/alibaba/Sentinel/releases/tag/1.8.6

2、nacos版本:2.1.2,下载地址:https://github.com/alibaba/nacos/releases

3、JDK版本:jdk1.8.0_351,下载地址 http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

4、SpringBoot、SpringCloud、SpringCloudAlibaba版本

​ 参考https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E

SpringBoot版本spring.cloud.alibaba版本spring.cloud版本
2.4.22021.12020.0.1

生产环境规则管理及推送一般更常用的是 push 模式的数据源。对于 push 模式的数据源,如远程配置中心(ZooKeeper, Nacos, Apollo等等),推送的操作不应由 Sentinel 客户端进行,而应该经控制台统一进行管理,直接进行推送,数据源仅负责获取配置中心推送的配置并更新到本地。因此推送规则正确做法应该是 配置中心控制台/Sentinel 控制台 → 配置中心 → Sentinel 数据源 → Sentinel,而不是经 Sentinel 数据源推送至配置中心,本文采用Nacos作为数据源

1、下载地址sentinel-dashboard:

https://github.com/alibaba/Sentinel/releases/tag/1.8.6

2、修改文件pom文件

打开sentinel-dashboard模块下的pom文件,把nacos的test作用域注释掉

       <!-- for Nacos rule publisher sample -->
       <dependency>
           <groupId>com.alibaba.csp</groupId>
           <artifactId>sentinel-datasource-nacos</artifactId>
<!--            <scope>test</scope>-->
       </dependency>
3、移动nacos推送和拉取规则实现示例文件

将test文件夹下 com.alibaba.csp.sentinel.dashboard.rule.nacos 包下的类移动到main文件com.alibaba.csp.sentinel.dashboard.rule
在这里插入图片描述


FlowRuleNacosProvider.java:从Nacos配置中心动态获取流控规则
FlowRuleNacosPublisher.java:上传动态获取流控规则到Nacos配置中心
NacosConfig.java:nacos配置
NacosConfigUtils.java:流控规则相关配置,比如GROUP_ID 流控规则的后缀FLOW_DATA_ID_POSTFIX

4、修改nacos配置文件

在NacosConfig中使用的是本地的nacos,我们需要修改此配置

在com.alibaba.csp.sentinel.dashboard.rule.nacos路径下创建NacosProperties.java文件,内容如下

package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "sentinel.nacos")
public class NacosProperties {

   /**
    * nacos地址
    */
   private String serverAddr;
   /**
    * nacos命名空间
    */
   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;
   }
}

修改NacosConfig.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;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Properties;

/**
* @author Eric Zhao
* @since 1.4.0
*/
@Configuration
public class NacosConfig {

   //注入nacos配置文件
   @Autowired
   private NacosProperties nacosProperties;

   @Bean
   public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {
       return JSON::toJSONString;
   }

   @Bean
   public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
       return s -> JSON.parseArray(s, FlowRuleEntity.class);
   }

   @Bean
   public ConfigService nacosConfigService() throws Exception {
//        修改前
//        return ConfigFactory.createConfigService("localhost");
//        修改后
       Properties properties = new Properties();
       properties.put(PropertyKeyConst.SERVER_ADDR, nacosProperties.getServerAddr());
       properties.put(PropertyKeyConst.NAMESPACE, nacosProperties.getNamespace());
       return ConfigFactory.createConfigService(properties);
   }
}

默认 Nacos 适配的 dataId 和 groupId 约定如下:

  • groupId: SENTINEL_GROUP
  • 流控规则 dataId: {appName}-flow-rules,比如应用名为 appA,则 dataId 为 appA-flow-rules

可以在 NacosConfigUtil 修改对应的 groupId 和 dataId postfix。然后在 NacosConfig 配置对应的 Converter,默认已提供 FlowRuleEntity 的 decoder 和 encoder。

最后在后端 com.alibaba.csp.sentinel.dashboard.controller.v2.FlowControllerV2 中指定对应的 bean 即可开启 Nacos 适配


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

至此、后端配置修改完成!!!

5、前端文件路由修改

官网原话:前端页面需要手动切换,或者修改前端路由配置(sidebar.html 流控规则路由从 dashboard.flowV1 改成 dashboard.flow 即可,注意簇点链路页面对话框需要自行改造)

a、修改流控规则

按照提示,找到resources/app/scripts/directives/sidebar/sidebar.html文件搜索dashboard.flowV1,进行修改

         <!--  修改前 -->
<!--          <li ui-sref-active="active" ng-if="!entry.isGateway">-->
<!--            <a ui-sref="dashboard.flowV1({app: entry.app})">-->
<!--              <i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控规则</a>-->
<!--          </li>-->
         <!--  修改后 -->
         <li ui-sref-active="active" ng-if="!entry.isGateway">
           <a ui-sref="dashboard.flow({app: entry.app})">
             <i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控规则</a>
         </li>

b、修改簇点链路

可以根据F12查看调用的接口然后确定页面修改方法即可

找到resources/app/scripts/controllers/identity.js文件,把FlowServiceV1 改成FlowServiceV2

image-20221128181749623

通页面找到saveFlowRule方法进行改动,把/dashboard/flow/换成/dashboard/v2/flow/

   function saveFlowRule() {
     if (!FlowService.checkRuleValid(flowRuleDialogScope.currentRule)) {
       return;
     }
     FlowService.newRule(flowRuleDialogScope.currentRule).success(function (data) {
       if (data.code === 0) {
         flowRuleDialog.close();
//          let url = '/dashboard/flow/' + $scope.app; //修改前
         let url = '/dashboard/v2/flow/' + $scope.app;//修改后
         $location.path(url);
       } else {
         alert('失败:' + data.msg);
       }
     }).error((data, header, config, status) => {
         alert('未知错误');
     });
   }
6、启动项目看看效果

按照上面的步骤已经改完了,启动项目看看效果

修改resource下面的application.properties文件,把一些常用的配置加上,我的加了下面这些

#项目参数
server.port=7080
csp.sentinel.dashboard.server=127.0.0.1:7080
project.name=sentinel-dashboard

#nacos配置
sentinel.nacos.serverAddr=127.0.0.1:8848
sentinel.nacos.namespace=7f1a800b-6fb5-444e-baf9-ca17a7e3ce76

如果需要加其他配置的可以参考官网控制台配置项

运行DashboardApplication的main方法启动,

浏览器打开http://127.0.0.1:7080/#/login登陆,用户名密码都是sentinel

image-20221128174132757

看到这个说明启动成功,接着搞个测试项目

7、创建演示项目

a、引入相关jar文件

<dependency>
   <groupId>com.alibaba.cloud</groupId>
   <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--   引入nacos数据源     -->
<dependency>
   <groupId>com.alibaba.csp</groupId>
   <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

b、配置文件

spring:
 application:
   name: sentinel-demo
 cloud:
   nacos:
     discovery:
       server-addr: 127.0.0.1:8848
       namespace: 7f1a800b-6fb5-444e-baf9-ca17a7e3ce76
   sentinel:
     transport:
       port: 8719
       dashboard: 127.0.0.1:7080
     datasource:
       flow:
         nacos:
           server-addr: 127.0.0.1:8848
           namespace: 7f1a800b-6fb5-444e-baf9-ca17a7e3ce76
           dataId: ${spring.application.name}-flow-rules
           groupId: SENTINEL_GROUP
           dataType: json
           rule-type: flow

namespace与控制台项目中sentinel.nacos.namespace配置项保持一样

dataId按照约定规则{appName}-flow-rules,比如应用名为 sentinel-demo,则 dataId 为 sentinel-demo-flow-rules

groupId与控制台项目中NacosConfigUtil的GROUP_ID一致

c、启动演示项目,随便调用一个接口

image-20221128182003922

新增一个流控规则

image-20221128182117271

image-20221128182336693

去nacos控制台查看。可以看到新增的规则

image-20221128182215627

ok,大功告成,这时候就算重启应用规则也不会消失
最后流控规则页面有个“回到单击页面 ”这个按钮,你要是点击了,那么又会回到默认的内存管理方式,所以我直接干掉他
找到resources/app/views/flow_v2.html ,找到回到单机页面按钮,直接注释掉这个按钮

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

滚动的小薯条

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值