Sentinel动态配置

一、动态配置常见方式:

image.png

1.原理:

控制台推送规则就是将规则推送至配置中心(nacos、apollo),sentinel客户端连接nacos,获取规则配置;并监听nacos配置变化,若发生变化,拉取规则更新本地缓存(从而让本地缓存总是和配置中心保持一致)。
·拉模式:客户端主动向某个规则管理中心定期轮询拉取规则,这个规则中心可以是RDBMS、文件、甚至是VCS等,这样做的方式很简单,缺点是无法及时获取更改。

image.png

·推模式:规则中心统一推送,客户端通过注册监听器的方式时刻监听变化,比如使用nacos、zookeeper、Apollo等配置中心。这种方式有更好的实时性和一致性。

image.png

二、动态配置实现

1.pull模式的数据源:

pull 模式的数据源(如本地文件、RDBMS 等)一般是可写入的。使用时需要在客户端注册数据源:将对应的读数据源注册至对应的RuleManager中,将写数据源注册至transport的WriteableDataSourceRegistry中,以本地文件数据源为例:

public class FileDataSourceInit implements InitFunc {

    @Override
    public void init() throws Exception {
        // A fake path.
        String flowRuleDir = System.getProperty("user.home") + File.separator + "sentinel" + File.separator + "rules";
        String flowRuleFile = "flowRule.json";
        String flowRulePath = flowRuleDir + File.separator + flowRuleFile;

        ReadableDataSource> ds = new FileRefreshableDataSource<>(
            flowRulePath, source -> JSON.parseObject(source, new TypeReference>() {})
        );
        // Register to flow rule manager.
        FlowRuleManager.register2Property(ds.getProperty());

        WritableDataSource> wds = new FileWritableDataSource<>(flowRulePath, this::encodeJson);
        // Register to writable data source registry so that rules can be updated to file
        // when there are rules pushed from the Sentinel Dashboard.
        WritableDataSourceRegistry.registerFlowDataSource(wds);
    }

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

2、与nacos结合实现动态配置:

pom文件中


            org.springframework.cloud
            spring-cloud-starter-alibaba-sentinel
        

        
            com.alibaba.csp
            sentinel-datasource-nacos
            1.7.2
        

yml文件中

spring:
  application:
    name: sentinel-server
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080

      datasource:
        dsl:
          nacos:
            server-addr: 127.0.0.1:8848
            #data-id: ${spring.application.name}-sentinel-flow
            data-id: gzf-sentinel-flow
            group-id: DEFAULT_GROUP
            data-type: json
            rule-type: flow

在controller写一个接口:


image.png

在nacos中配置规则:

image.png

sentinel控制台可以看到:

image.png

你可能感兴趣的:(Sentinel动态配置)