sentinel本地文件跟控制台实现双向持久化

重写spi路径

注意路径不能出错 
 里面指定配置类路径
配置类代码如下
 

package com.aspirecn.bfms.sms.config;

import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.datasource.FileWritableDataSource;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * SentinelPerFile类用于Sentinel的规则持久化.
 * <p>
 * 通过从指定的JSON文件中读取各类规则并进行注册.
 * 同时注册了可写数据源以便在控制台推送规则时,Sentinel可以将规则写入到文件中.
 */
@Component
public class SentinelPerFile implements InitFunc {

    private static final Logger LOGGER = LoggerFactory.getLogger(SentinelPerFile.class);

    @Override
    public void init() throws Exception {
        LOGGER.info("开始初始化Sentinel规则");
        String ruleDir = new File("src/main/resources/sentinelFile/sentinel/rules").getAbsolutePath();
//        String ruleDir = classpath +"${basedir}/src/main/resources/sentinelFile/sentinel/rules";
//        String ruleDir = "sentinelFile/sentinel/rules";classpath*:mapper/*.xml

        String flowRulePath = ruleDir + "/flow-rule.json";
        String degradeRulePath = ruleDir + "/degrade-rule.json";
        String systemRulePath = ruleDir + "/system-rule.json";
        String authorityRulePath = ruleDir + "/authority-rule.json";
        String paramFlowRulePath = ruleDir + "/param-flow-rule.json";

        createDirectoryIfNotExits(ruleDir);
        createFileIfNotExits(flowRulePath);
        createFileIfNotExits(degradeRulePath);
        createFileIfNotExits(systemRulePath);
        createFileIfNotExits(authorityRulePath);
        createFileIfNotExits(paramFlowRulePath);

        registerRules(flowRulePath, degradeRulePath, systemRulePath, authorityRulePath, paramFlowRulePath);

        LOGGER.info("完成Sentinel规则初始化");
    }

    /**
     * 注册Sentinel规则.
     *
     * @param flowRulePath      流控规则文件路径
     * @param degradeRulePath   降级规则文件路径
     * @param systemRulePath    系统规则文件路径
     * @param authorityRulePath 授权规则文件路径
     * @param paramFlowRulePath 热点参数规则文件路径
     * @throws Exception 异常
     */
    private void registerRules(String flowRulePath, String degradeRulePath, String systemRulePath, String authorityRulePath, String paramFlowRulePath) throws Exception {
        // 注册流控规则
        registerFlowRule(flowRulePath);
        // 注册降级规则
        registerDegradeRule(degradeRulePath);
        // 注册系统规则
        registerSystemRule(systemRulePath);
        // 注册授权规则
        registerAuthorityRule(authorityRulePath);
        // 注册热点参数规则
        registerParamFlowRule(paramFlowRulePath);
    }

    private void registerFlowRule(String flowRulePath) throws FileNotFoundException {
        ReadableDataSource<String, List<FlowRule>> flowRuleRDS =
                new FileRefreshableDataSource<>(flowRulePath, this::decodeFlowRuleList);
        FlowRuleManager.register2Property(flowRuleRDS.getProperty());
        WritableDataSource<List<FlowRule>> flowRuleWDS = new FileWritableDataSource<>(flowRulePath, this::encodeJson);
        WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS);
    }

    private void registerDegradeRule(String degradeRulePath) throws FileNotFoundException {
        ReadableDataSource<String, List<DegradeRule>> degradeRuleRDS = new FileRefreshableDataSource<>(degradeRulePath, this::decodeDegradeRuleList);
        DegradeRuleManager.register2Property(degradeRuleRDS.getProperty());
        WritableDataSource<List<DegradeRule>> degradeRuleWDS = new FileWritableDataSource<>(degradeRulePath, this::encodeJson);
        WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS);
    }

    private void registerSystemRule(String systemRulePath) throws FileNotFoundException {
        ReadableDataSource<String, List<SystemRule>> systemRuleRDS = new FileRefreshableDataSource<>(systemRulePath, this::decodeSystemRuleList);
        SystemRuleManager.register2Property(systemRuleRDS.getProperty());
        WritableDataSource<List<SystemRule>> systemRuleWDS = new FileWritableDataSource<>(systemRulePath, this::encodeJson);
        WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS);
    }

    private void registerAuthorityRule(String authorityRulePath) throws FileNotFoundException {
        ReadableDataSource<String, List<AuthorityRule>> authorityRuleRDS = new FileRefreshableDataSource<>(authorityRulePath, this::decodeAuthorityRuleList);
        AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty());
        WritableDataSource<List<AuthorityRule>> authorityRuleWDS = new FileWritableDataSource<>(authorityRulePath, this::encodeJson);
        WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS);
    }

    private void registerParamFlowRule(String paramFlowRulePath) throws FileNotFoundException {
        ReadableDataSource<String, List<ParamFlowRule>> paramFlowRuleRDS = new FileRefreshableDataSource<>(paramFlowRulePath, this::decodeParamFlowRuleList);
        ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty());
        WritableDataSource<List<ParamFlowRule>> paramFlowRuleWDS = new FileWritableDataSource<>(paramFlowRulePath, this::encodeJson);
        ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS);
    }

    private List<FlowRule> decodeFlowRuleList(String source) {
        return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
        });
    }

    private List<DegradeRule> decodeDegradeRuleList(String source) {
        return JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {
        });
    }

    private List<SystemRule> decodeSystemRuleList(String source) {
        return JSON.parseObject(source, new TypeReference<List<SystemRule>>() {
        });
    }

    private List<AuthorityRule> decodeAuthorityRuleList(String source) {
        return JSON.parseObject(source, new TypeReference<List<AuthorityRule>>() {
        });
    }

    private List<ParamFlowRule> decodeParamFlowRuleList(String source) {
        return JSON.parseObject(source, new TypeReference<List<ParamFlowRule>>() {
        });
    }

    /**
     * 创建目录,如果不存在.
     *
     * @param directoryPath 目录路径
     * @throws IOException 异常
     */
    private void createDirectoryIfNotExits(String directoryPath) throws IOException {
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            if (directory.mkdirs()) {
                LOGGER.info("创建目录: " + directoryPath);
            } else {
                LOGGER.error("无法创建目录: " + directoryPath);
                throw new IOException("无法创建目录: " + directoryPath);
            }
        }
    }

    /**
     * 创建文件,如果不存在.
     *
     * @param filePath 文件路径
     * @throws IOException 异常
     */
    private void createFileIfNotExits(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            if (file.createNewFile()) {
                LOGGER.info("创建文件: " + filePath);
            } else {
                LOGGER.error("无法创建文件: " + filePath);
                throw new IOException("无法创建文件: " + filePath);
            }
        }
    }

    /**
     * 将对象转换为JSON字符串.
     *
     * @param object 要转换的对象
     * @return JSON字符串
     */
    private <T> String encodeJson(T object) {
        return JSON.toJSONString(object);
    }
}

测试验证  完事

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sentinel 控制台是一个基于 Spring Cloud 的应用,它提供了一个可视化的界面来管理和监控 Sentinel 的流控规则、降级规则、系统规则等。而 Nacos 是一个开源的注册中心和配置中心,它提供了服务注册、配置管理和服务发现等功能。将 Sentinel 控制台持久化到 Nacos 可以实现Sentinel 控制台配置的动态管理和版本控制。 将 Sentinel 控制台持久化到 Nacos,需要进行以下步骤: 1. 在 Nacos 控制台中创建一个命名空间和配置集,用来保存 Sentinel 控制台的配置信息。 2. 在 Sentinel 控制台的 application.properties 配置文件中,添加以下配置: ``` # 配置 Nacos 的服务地址和命名空间 spring.cloud.nacos.config.server-addr=<Nacos 服务地址> spring.cloud.nacos.config.namespace=<Nacos 命名空间> # 配置 Sentinel 控制台的配置信息 spring.cloud.sentinel.transport.dashboard=localhost:8080 management.endpoints.web.exposure.include=sentinel spring.cloud.sentinel.eager=true ``` 3. 在 Sentinel 控制台启动后,访问 http://localhost:8080/nacos/config 会自动将 Sentinel 控制台的配置信息保存到 Nacos 中。 4. 在 Nacos 控制台中修改 Sentinel 控制台的配置信息,可以实现Sentinel 控制台配置的动态管理和版本控制。 需要注意的是,将 Sentinel 控制台持久化到 Nacos 需要使用 Sentinel 控制台的 1.8.0 版本及以上,同时需要安装 Nacos 的配置中心服务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值