Sentinel规则持久化进Nacos

源码地址:gitee代码仓库地址

1、为什么要将Sentienl规则持久化?

  一旦我们重启应用,sentinel规则将消失,生产环境需要将配置规则进行持久化

2、持久化的思路

  我们现在将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台的流控规则就能看到,只要Nacos里面的配置不删除,针对8401上sentinel上的流控规则持续有效。

image-20220418235002262

3、操作步骤

3.1 项目中引入依赖

<!--SpringCloud ailibaba sentinel-datasource-nacos -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

image-20220418235233305

3.2 添加Nacos数据源配置

application.yml

server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        #Nacos服务注册中心地址
        server-addr: localhost:8848
    sentinel:
      transport:
        #配置Sentinel dashboard地址
        dashboard: localhost:8080
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719
      datasource:
        ds1:  #添加nacos数据源的配置,将sentinel配置持久化进nacos里面
          nacos:
            server-addr: localhost:8848
            dataId: cloudalibaba-sentinel-service
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow

management:
  endpoints:
    web:
      exposure:
        include: '*'

image-20220418235401928

3.3 添加Nacos业务规则配置

image-20220418235500942

[
    {
    
    
        "resource": "/rateLimit/byUrl",
        "limitApp": "default",
        "grade": 1,
        "count": 1,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]

resource:资源名称;
limitApp:来源应用;
grade:阈值类型,0表示线程数,1表示QPS;
count:单机阈值;
strategy:流控模式,0表示直接,1表示关联,2表示链路;
controlBehavior:流控效果,0表示快速失败,1表示Warm Up,2表示排队等待;
clusterMode:是否集群。

3.4 启动sentinel

image-20220419000131789

3.5 此时启动8401微服务并刷新Sentinel

  发现业务规则有了。

  nacos上面:

image-20220418235653750

  sentinel上面:

image-20220419000248314

3.6 测试

  我们上面配置的意思是,该接口每秒只能处理1个请求,那我们频繁刷新请求,看看限流规则是否生效。

  先正常访问:http://localhost:8401/rateLimit/byUrl

image-20220419000432680

  频繁访问:http://localhost:8401/rateLimit/byUrl

image-20220419000459402

  可以看到,触发了限流规则。这里我们程序中并没有指定blockHandler,所以显示的是默认限流之后的信息。

3.7 停止8401微服务查看

image-20220419000837695

  停止8401发现流控规则没有了。

3.8 重启8401微服务再看sentinel

image-20220419000949053

  还是没有,我们访问一次http://localhost:8401/rateLimit/byUrl,再刷新Sentinel

image-20220419001028817

  配置出现了,持久化验证通过。

猜你喜欢

转载自blog.csdn.net/qq_43753724/article/details/124263104