资讯专栏INFORMATION COLUMN

[Spring-Cloud-Alibaba] Sentinel 规则持久化

only_do / 1496人阅读

摘要:在之前的练习中,只要应用重启,就需要重新配置,这样在我们实际的项目是非常不实用的,那么有没有办法把我们配置的规则保存下来呢答案是,那么接下来,给大家来介绍如何将规则持久化。重新启动测试效果添加流控规则查看同步的配置

在之前的练习中,只要应用重启,就需要重新配置,这样在我们实际的项目是非常不实用的,那么有没有办法把我们配置的规则保存下来呢?答案是YES,那么接下来,给大家来介绍如何将Sentinel规则持久化。

Document: 传送门

File Datasource(文件存储)

Pull 模式

Push 模式

Nacos configuration

Apollo

File Datasource
Pull 模式
原理:
扩展写数据源(WritableDataSource), 客户端主动向某个规则管理中心定期轮询拉取规则,这个规则中心可以是 RDBMS、文件 等
pull 模式的数据源(如本地文件、RDBMS 等)一般是可写入的。使用时需要在客户端注册数据源:将对应的读数据源注册至对应的 RuleManager,将写数据源注册至 transport 的 WritableDataSourceRegistry 中。

过程如下:

Pull Demo

Step 1: 添加配置

    
        com.alibaba.csp
        sentinel-datasource-extension
    

Step 2: 编写持久化代码,实现com.alibaba.csp.sentinel.init.InitFunc

代码参考自:传送门

import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
import com.alibaba.csp.sentinel.datasource.*;
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.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

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

/**
 * FileDataSourceInit for : 自定义Sentinel存储文件数据源加载类
 *
 * @author Isaac.Zhang | 若初
 * @since 2019/7/21
 */
public class FileDataSourceInit implements InitFunc {
    @Override
    public void init() throws Exception {
        // TIPS: 如果你对这个路径不喜欢,可修改为你喜欢的路径
        String ruleDir = System.getProperty("user.home") + "/sentinel/rules";
        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 hotParamFlowRulePath = ruleDir + "/param-flow-rule.json";

        this.mkdirIfNotExits(ruleDir);
        this.createFileIfNotExits(flowRulePath);
        this.createFileIfNotExits(degradeRulePath);
        this.createFileIfNotExits(systemRulePath);
        this.createFileIfNotExits(authorityRulePath);
        this.createFileIfNotExits(hotParamFlowRulePath);
        // 流控规则
        ReadableDataSource> flowRuleRDS = new FileRefreshableDataSource<>(
                flowRulePath,
                flowRuleListParser
        );
        // 将可读数据源注册至FlowRuleManager
        // 这样当规则文件发生变化时,就会更新规则到内存
        FlowRuleManager.register2Property(flowRuleRDS.getProperty());
        WritableDataSource> flowRuleWDS = new FileWritableDataSource<>(
                flowRulePath,
                this::encodeJson
        );
        // 将可写数据源注册至transport模块的WritableDataSourceRegistry中
        // 这样收到控制台推送的规则时,Sentinel会先更新到内存,然后将规则写入到文件中
        WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS);

        // 降级规则
        ReadableDataSource> degradeRuleRDS = new FileRefreshableDataSource<>(
                degradeRulePath,
                degradeRuleListParser
        );
        DegradeRuleManager.register2Property(degradeRuleRDS.getProperty());
        WritableDataSource> degradeRuleWDS = new FileWritableDataSource<>(
                degradeRulePath,
                this::encodeJson
        );
        WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS);

        // 系统规则
        ReadableDataSource> systemRuleRDS = new FileRefreshableDataSource<>(
                systemRulePath,
                systemRuleListParser
        );
        SystemRuleManager.register2Property(systemRuleRDS.getProperty());
        WritableDataSource> systemRuleWDS = new FileWritableDataSource<>(
                systemRulePath,
                this::encodeJson
        );
        WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS);

        // 授权规则
        ReadableDataSource> authorityRuleRDS = new FileRefreshableDataSource<>(
                flowRulePath,
                authorityRuleListParser
        );
        AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty());
        WritableDataSource> authorityRuleWDS = new FileWritableDataSource<>(
                authorityRulePath,
                this::encodeJson
        );
        WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS);

        // 热点参数规则
        ReadableDataSource> hotParamFlowRuleRDS = new FileRefreshableDataSource<>(
                hotParamFlowRulePath,
                hotParamFlowRuleListParser
        );
        ParamFlowRuleManager.register2Property(hotParamFlowRuleRDS.getProperty());
        WritableDataSource> paramFlowRuleWDS = new FileWritableDataSource<>(
                hotParamFlowRulePath,
                this::encodeJson
        );
        ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS);
    }

    /**
     * 流控规则对象转换
     */
    private Converter> flowRuleListParser = source -> JSON.parseObject(
            source,
            new TypeReference>() {
            }
    );
    /**
     * 降级规则对象转换
     */
    private Converter> degradeRuleListParser = source -> JSON.parseObject(
            source,
            new TypeReference>() {
            }
    );
    /**
     * 系统规则对象转换
     */
    private Converter> systemRuleListParser = source -> JSON.parseObject(
            source,
            new TypeReference>() {
            }
    );

    /**
     * 授权规则对象转换
     */
    private Converter> authorityRuleListParser = source -> JSON.parseObject(
            source,
            new TypeReference>() {
            }
    );

    /**
     * 热点规则对象转换
     */
    private Converter> hotParamFlowRuleListParser = source -> JSON.parseObject(
            source,
            new TypeReference>() {
            }
    );

    /**
     * 创建目录
     *
     * @param filePath
     */
    private void mkdirIfNotExits(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 创建文件
     *
     * @param filePath
     * @throws IOException
     */
    private void createFileIfNotExits(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
        }
    }

    private  String encodeJson(T t) {
        return JSON.toJSONString(t);
    }
}

Step 3: 启用上述代码

resource 目录下创建 resources/META-INF/services 目录并创建文件com.alibaba.csp.sentinel.init.InitFunc ,内容为:

com.sxzhongf.sharedcenter.configuration.sentinel.datasource.FileDataSourceInit

Pull 优缺点

优点

简单,无任何依赖

没有额外依赖

缺点

不保证一致性(规则是使用FileRefreshableDataSource定时更新,会有延迟)

实时性不保证(规则是使用FileRefreshableDataSource定时更新)

拉取过于频繁也可能会有性能问题

由于文件存储于本地,容易丢失

参考资料:

ITMUCH

Sentinel WIKI

Push 模式
推荐通过控制台设置规则后将规则推送到统一的规则中心,客户端实现 ReadableDataSource接口端监听规则中心实时获取变更,流程如下:

实现原理

控制台推送规则到Nacos/远程配置中心

Sentinel client 舰艇Nacos配置变化,更新本地缓存

shared_center service 加工

添加依赖

  
      com.alibaba.csp
      sentinel-datasource-nacos
  

添加配置

spring:
  cloud:
    sentinel:
      datasource:
        sxzhongf_flow:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-flow-rules
            groupId: SENTINEL_GROUP
            # 规则类型,取值见:org.springframework.cloud.alibaba.sentinel.datasource.RuleType
            rule_type: flow
        sxzhongf_degrade:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-degrade-rules
            groupId: SENTINEL_GROUP
            rule-type: degrade

Sentinel dashboard 加工

Dashboard 规则改造主要通过2个接口:

com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider & com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher

Download Sentinel Source Code

修改原sentinel-dashboard项目下的POM文件

    
    
        com.alibaba.csp
        sentinel-datasource-nacos
        
        
    

偷懒模式:复制sentinel-dashboard项目下test下的nacos包(

src/test/java/com/alibaba/csp/sentinel/dashboard/rule/nacossrc/main/java/com/alibaba/csp/sentinel/dashboard/rule

修改controller中的默认provider & publisher

com.alibaba.csp.sentinel.dashboard.controller.v2.FlowControllerV2

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

打开 /Sentinel-1.6.2/sentinel-dashboard/src/main/webapp/resources/app/scripts/directives/sidebar/sidebar.html文件,修改代码:


            
              


---

改为

  
  •   NACOS 流控规则 V1
  • Dashboard中要修改的代码已经好了。

    重新启动 Sentinel-dashboard mvn clean package -DskipTests

    测试效果

    Sentinel 添加流控规则:

    Nacos 查看同步的配置:

    文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

    转载请注明本文地址:https://www.ucloud.cn/yun/75534.html

    相关文章

    • Spring Cloud Alibaba整合Sentinel流控

      摘要:前面我们都是直接通过集成的依赖,通过编码的方式配置规则等。对于集成到中阿里已经有了一套开源框架,就是用于将一系列的框架成功的整合到中。但这也是在学习过程中遇到的一个问题,还是得通过调试源码的方式去发现问题的原因。 前面我们都是直接通过集成sentinel的依赖,通过编码的方式配置规则等。对于集成到Spring Cloud中阿里已经有了一套开源框架spring-cloud-alibaba...

      ytwman 评论0 收藏0
    • [Spring-Cloud-Alibaba] Sentinel 整合RestTemplate &am

      摘要:开发阶段很有意义。源码整合配置文件中添加来开启编写类,实现默认用户远程调用被限流降级,默认用户应用定义可以拿到异常信息无法拿到异常信息若初启动应用,设置流控规则,结果展示如下默认用户源码 Sentinel API Github : WIKI Sphu (指明要保护的资源名称) Tracer (指明调用来源,异常统计接口) ContextUtil(标示进入调用链入口) 流控规则(针...

      libin19890520 评论0 收藏0
    • springcloud(二)——spring-cloud-alibaba集成sentinel入门

      摘要:介绍随着微服务的流行,服务和服务之间的稳定性变得越来越重要。以流量为切入点,从流量控制熔断降级系统负载保护等多个维度保护服务的稳定性。完备的实时监控同时提供实时的监控功能。您只需要引入相应的依赖并进行简单的配置即可快速地接入。 Sentinel 介绍 随着微服务的流行,服务和服务之间的稳定性变得越来越重要。 Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度...

      darkbug 评论0 收藏0
    • Spring Cloud Alibaba基础教程:Sentinel使用Nacos存储规则

      摘要:所以,在整合了做规则存储之后,需要知道在下面两个地方修改存在不同的效果控制台中修改规则仅存在于服务的内存中,不会修改中的配置值,重启后恢复原来的值。控制台中修改规则服务的内存中规则会更新,中持久化规则也会更新,重启后依然保持。 通过上一篇《使用Sentinel实现接口限流》的介绍,相信大家对Sentinel已经有了初步的认识。在Spring Cloud Alibaba的整合封装之下,接...

      xingqiba 评论0 收藏0
    • 阿里Sentinel控制台源码修改-对接Apollo规则久化

      摘要:改造背景前面我们讲解了如何对接来持久化限流的规则,对接后可以直接通过的后台进行规则的修改,推送到各个客户端实时生效。因此推送规则正确做法应该是配置中心控制台控制台配置中心数据源,而不是经数据源推送至配置中心。 改造背景 前面我们讲解了如何对接Apollo来持久化限流的规则,对接后可以直接通过Apollo的后台进行规则的修改,推送到各个客户端实时生效。 但还有一个问题就是Sentinel...

      zhoutao 评论0 收藏0

    发表评论

    0条评论

    only_do

    |高级讲师

    TA的文章

    阅读更多
    最新活动
    阅读需要支付1元查看
    <