文章目录


目录

文章目录

前言

一、方案实现思路

二、具体实现

1.application.yaml

2.CustomSentinelProperties配置文件

        3.自定义service服务

           CustomConfigService

           CustomSentinelService



前言

网上很多改造dashboard源码直接和nacos同步,然后sentinel再和nacos同步的方案


但是总觉得有如下问题:

此功能既然已经再test代码了,也就是以后也必定会发布,此时对固定版本改造可用,然后等待官方发布了新版,如果还没发布此功能,又得重新找一个对应的版本自定义改造,实在是麻烦,何不制作一个小代价的更新版本,既合适新版升级,又代价不太大的。

可以实现
(1)代价不大,不比对所有复杂的配置进行一一翻译,万一官方升级了,工作就浪费了
(2)可以适配官方升级

一、方案实现思路

方案实现思路:

(读取) sentinel客户端 <------读取----nacos的 json配置 (官方提供)

(写入)  dashboard--->写入--->entinel客户端--->写入--->nacos的 json配置

一句话概括就是sentinel客户端- 调用自定义的nacos的自定义方法,写入json,只要一个客户端更新了,nacos再群发回调集群的所有sentinel客户端,集体更新(包括提交更新的客户端)

大概操作方式就是先用dashboard进行更新,此时更新配置已经在sentinel客户端内存类了,调用sentinel客户端方法进行保存(Contorller)完成数据更新

二、具体实现

1.application.yaml

spring:
  application:
    name: chris-sentinel-service
  cloud:
    nacos:
      server-addr: 192.168.100.254:8848
      username: nacos
      password: nacos
    sentinel:
      transport:
        port: 8719
        dashboard: 192.168.100.254:8087
        #clientIp: 192.168.100.14
      datasource: #重点:在sentinel客户端配置nacs的连接地址等限流信息
        flow-ds:
          nacos:
            server-addr: 192.168.100.254:8848
            dataId: ${custom-sensinel.flow-rule.data-id}
            groupId: ${custom-sensinel.flow-rule.group}
            data-type: json
            rule-type: flow
        degrade-ds:
          nacos:
            server-addr: 192.168.100.254:8848
            dataId: ${custom-sensinel.degrade-rule.data-id}
            groupId: ${custom-sensinel.degrade-rule.group}
            data-type: json
            rule-type: degrade
      eager: true


#自定义更新和加载 sensinel
custom-sensinel:
  flow-rule:
    data-id: "chris-sentinel-flow"
    group: "CONFIG_GROUP"
  degrade-rule:
    data-id: "chris-sentinel-degrade"
    group: "CONFIG_GROUP"
  system-rule:
    data-id: "chris-sentinel-system"
    group: "CONFIG_GROUP"
  paramFlow-rule:
    data-id: "chris-sentinel-paramFlow"
    group: "CONFIG_GROUP"
  authority-rule:
    data-id: "chris-sentinel-authority"
    group: "CONFIG_GROUP"

2.CustomSentinelProperties配置文件

/**
 * 自定义sentinel配置属性
 */
@ConfigurationProperties(prefix = "custom-sensinel")
@Component
public class CustomSentinelProperties {

    /**
     * 流量控制规则 (FlowRule)
     */
    private CustomSensinel flowRule;

    /**
     * 熔断降级规则 (DegradeRule)
     */
    private CustomSensinel degradeRule;

    /**
     * 系统保护规则 (SystemRule)
     */
    private CustomSensinel systemRule;

    /**
     * 访问控制规则 (AuthorityRule)
     */
    private CustomSensinel authorityRule;

    /**
     * 热点规则 (ParamFlowRule)
     */
    private CustomSensinel paramFlowRule;

    public CustomSensinel getDegradeRule() {
        return degradeRule;
    }

    public void setDegradeRule(CustomSensinel degradeRule) {
        this.degradeRule = degradeRule;
    }

    public CustomSensinel getSystemRule() {
        return systemRule;
    }

    public void setSystemRule(CustomSensinel systemRule) {
        this.systemRule = systemRule;
    }

    public CustomSensinel getAuthorityRule() {
        return authorityRule;
    }

    public void setAuthorityRule(CustomSensinel authorityRule) {
        this.authorityRule = authorityRule;
    }

    public CustomSensinel getParamFlowRule() {
        return paramFlowRule;
    }

    public void setParamFlowRule(CustomSensinel paramFlowRule) {
        this.paramFlowRule = paramFlowRule;
    }

    public CustomSensinel getFlowRule() {
        return flowRule;
    }

    public void setFlowRule(CustomSensinel flowRule) {
        this.flowRule = flowRule;
    }

    public static class CustomSensinel {

        private String dataId;
        private String group;

        public String getDataId() {
            return dataId;
        }

        public void setDataId(String dataId) {
            this.dataId = dataId;
        }

        public String getGroup() {
            return group;
        }

        public void setGroup(String group) {
            this.group = group;
        }
    }
}

3.自定义service服务

      CustomConfigService

/**
 * nacos 自定义配置服务
 * 苏斌 2022-10-6
 */
//@Service
public class CustomConfigService {
    //private CustomConfigProperties configProperties;

    //@Autowired
    private NacosConfigProperties nacosConfigProperties;


    private ConfigService configService;

    /**
     * 构造函数
     * @param _nacosConfigProperties 注入系统nacos环境
     * @throws NacosException
     */
    public CustomConfigService(NacosConfigProperties _nacosConfigProperties) throws NacosException {
        //  configProperties=_configProperties;
        nacosConfigProperties = _nacosConfigProperties;

        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosConfigProperties.getServerAddr());
        if (nacosConfigProperties.getNamespace() != null)
            properties.setProperty(PropertyKeyConst.NAMESPACE,nacosConfigProperties.getNamespace());
        if (nacosConfigProperties.getUsername() != null)
            properties.setProperty(PropertyKeyConst.USERNAME, nacosConfigProperties.getUsername());
        if (nacosConfigProperties.getPassword() != null)
            properties.setProperty(PropertyKeyConst.PASSWORD, nacosConfigProperties.getPassword());
        configService = NacosFactory.createConfigService(properties);
    }

    /**
     * 读取配置
     * @param dataId
     * @param group
     * @return
     */
    public String GetConfig(String dataId,String group)
    {
        try {
            return configService.getConfig(dataId, group, 5000);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发布配置
     * @param dataId  dataId
     * @param group   group
     * @param content content
     * @param type    config type {@link ConfigType}
     * @return
     */
    public Boolean publishConfig(String dataId, String group, String content, String type) {
        try {
            return configService.publishConfig(dataId, group, content, type);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

     /**
     * 加入监听指针
     */
    public void AddlListen(String dataId, String group, Listener listener)
    {
        try {
            configService.addListener(dataId, group, listener);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 初始化函数
     */
    @PostConstruct
    public void IntSystem()
    {

    }


}

    CustomSentinelService

/**
 * 自定义Sentinel服务类 结合 nacos json
 * 苏斌
 * 2022-10-12
 */
@Service
public class CustomSentinelService {
    Logger log  = LoggerFactory.getLogger(CustomSentinelService.class);
    @Autowired
    CustomConfigService customConfigService;

    @Autowired
    CustomSentinelProperties customSentinelProperties;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 流量控制规则 (FlowRule)
     * @return
     */
    public boolean SaveFlowRule()
    {
        if (customSentinelProperties.getFlowRule()==null || customSentinelProperties.getFlowRule().getDataId()==null)
            return false;

        List<FlowRule> rules = FlowRuleManager.getRules();
        log.debug("保存 SaveFlowRule "+rules.toString());
        String content="[]";
        if (!rules.isEmpty()) {
            try {
                content = objectMapper.writeValueAsString(rules);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
       return customConfigService.publishConfig( customSentinelProperties.getFlowRule().getDataId(),  customSentinelProperties.getFlowRule().getGroup(),  content,  "json");
    }

    /**
     * 垄断降级规则
     * @return
     */
    public boolean SaveDegradeRule()
    {
        if (customSentinelProperties.getDegradeRule()==null || customSentinelProperties.getDegradeRule().getDataId()==null)
            return false;

        List<DegradeRule> rules = DegradeRuleManager.getRules();
        log.debug("保存 SaveDegradeRule "+rules.toString());
        String content="[]";
        if (!rules.isEmpty()) {
            try {
                content = objectMapper.writeValueAsString(rules);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return customConfigService.publishConfig( customSentinelProperties.getDegradeRule().getDataId(),  customSentinelProperties.getDegradeRule().getGroup(),  content,  "json");
    }

    /**
     * 系统保护规则 (SystemRule)
     * @return
     */
    public boolean SaveSystemRule()
    {
        if (customSentinelProperties.getSystemRule()==null || customSentinelProperties.getSystemRule().getDataId()==null)
            return false;

        List<SystemRule> rules = SystemRuleManager.getRules();
        log.debug("保存 SaveSystemRule "+rules.toString());
        String content="[]";
        if (!rules.isEmpty()) {
            try {
                content = objectMapper.writeValueAsString(rules);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return customConfigService.publishConfig( customSentinelProperties.getSystemRule().getDataId(),  customSentinelProperties.getSystemRule().getGroup(),  content,  "json");
    }

    /**
     * 访问控制规则 (AuthorityRule)
     * @return
     */
    public boolean SaveAuthorityRule()
    {
        if (customSentinelProperties.getAuthorityRule()==null || customSentinelProperties.getAuthorityRule().getDataId()==null)
            return false;

        List<AuthorityRule> rules = AuthorityRuleManager.getRules();
        log.debug("保存 SaveAuthorityRule "+rules.toString());
        String content="[]";
        if (!rules.isEmpty()) {
            try {
                content = objectMapper.writeValueAsString(rules);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return customConfigService.publishConfig( customSentinelProperties.getAuthorityRule().getDataId(),  customSentinelProperties.getAuthorityRule().getGroup(),  content,  "json");
    }

    /**
     * 热点规则 (ParamFlowRule)
     * @return
     */
    public boolean SaveParamFlowRule()
    {
        if (customSentinelProperties.getParamFlowRule()==null || customSentinelProperties.getParamFlowRule().getDataId()==null)
            return false;

        List<ParamFlowRule> rules = ParamFlowRuleManager.getRules();
        log.debug("保存 SaveParamFlowRule "+rules.toString());
        String content="[]";
        if (!rules.isEmpty()) {
            try {
                content = objectMapper.writeValueAsString(rules);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return customConfigService.publishConfig( customSentinelProperties.getParamFlowRule().getDataId(),  customSentinelProperties.getParamFlowRule().getGroup(),  content,  "json");
    }

}

最终nacos上效果

nacos 修改需要重启java服务吗_json

nacos 修改需要重启java服务吗_spring cloud_02