不改一行源码,基于本地文件实现跟sentinel的数据同步持久化

添加pom

        <!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-starter-alibaba-sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>${sentinel.version}</version>
        </dependency>

增加配置

    cloud:
        sentinel:
            transport:
                dashboard: localhost:8080
                port: 8720 #客户端监控API的端口
            eager: true #取消Sentinel控制台懒加载

添加文件夹

com.alibaba.csp.sentinel.init.InitFunc

注意路径指定配置类

配置类

/**
 * 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
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值