sentinel与nacos集成

前言

sentinel的规则可以通过编码方式定义,也可以通过配置方式定义。sentinel-dashboard提供了界面维护功能,但是配置是存储在内存中的。因此需要进行持久化。

Sentinel自身就支持了多种不同的数据源来持久化规则配置,目前包括以下几种方式:

  • 文件配置
  • Nacos配置
  • ZooKeeper配置
  • Apollo配置

注意:这些持久化只是指,客户端 能够从持久化存储中获取规则定义,sentinel-dashboard的界面维护的配置仍然是在内存中

准备工作

  • 准备Nacos环境
  • 准备sentinel-dashboard 环境

客户端使用Nacos存储

引入扩展

xml 复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-datasource-nacos</artifactId>
        <version>1.8.1</version>
    </dependency>
</dependencies>

指定sentinel配置

properties 复制代码
# sentinel dashboard
spring.cloud.sentinel.transport.dashboard=localhost:8080
# nacos 地址。
spring.cloud.sentinel.datasource.ds.nacos.server-addr=localhost:8848
#设置 sentinel的dataId。
spring.cloud.sentinel.datasource.ds.nacos.dataId=${spring.application.name}-sentinel
spring.cloud.sentinel.datasource.ds.nacos.groupId=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds.nacos.namespace=4392f929-fa22-4ea0-8cce-16a04b21d73f
spring.cloud.sentinel.datasource.ds.nacos.rule-type=flow

yaml配置

yaml 复制代码
spring:
  cloud:
    sentinel:
      transport:
        dashboard: 192.168.1.70:7990   #自己的sentinel dashboard url。
        #port: 8719                   # 这个port是client port,会显示在dashboard的机器列表中。发布的端口,可以通过 http://localhost:8719/getRules?type=<XXXX> 获取规则
      datasource: 
        ds:					#这是规则的id,自定义,唯一即可。
          nacos:
            server-addr: 192.168.1.54:8848
            namespace: 4392f929-fa22-4ea0-8cce-16a04b21d73f
            data-id: jurassic-sample-biz-sentinel
            group-id: DEFAULT_GROUP
            rule-type: flow

以上配置是放在启动配置中的,也可以把这些配置放在Nacos中。动态维护,而不需要每次更新配置。

2种方式 都需要 重启 服务。

在Nacos中配置规则

在Naocs中创建相关dataId,并在配置中输入以下内容:

json 复制代码
[
    {
        "resource": "/T1/sentinel",
        "limitApp": "default",
        "grade": 1,
        "count": 5,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]

Nacos的配置更新,会立即同步到客户端。

shell 复制代码
2024-02-04 16:55:50.702 INFO [NacosDataSource] New property value received for (properties: {namespace=4392f929-fa22-4ea0-8cce-16a04b21d73f, serverAddr=192.168.1.54:8848}) (dataId: jurassic-sample-biz-sentinel, groupId: DEFAULT_GROUP): [
    {
        "resource": "/T1/sentinel",
        "limitApp": "default",
        "grade": 1,
        "count": 0.5,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]

测试规则

1、启动

shell 复制代码
#表示已启动
024-02-04 10:49:15.502  INFO 10660 --- [           main] c.a.c.s.SentinelWebAutoConfiguration     : [Sentinel Starter] register SentinelWebInterceptor with urlPatterns: [/**].


2024-02-04 11:50:13.012 INFO [NacosDataSource] New property value received for (properties: {namespace=4392f929-fa22-4ea0-8cce-16a04b21d73f, serverAddr=192.168.1.54:8848}) (dataId: jurassic-sample-biz-sentinel, groupId: DEFAULT_GROUP): [
    {
        "resource": "/T1/sentinel",
        "limitApp": "default",
        "grade": 1,
        "count": 5,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]


2024-02-04 13:23:57.549 INFO [FlowRuleManager] Registering new property to flow rule manager
2024-02-04 13:23:57.552 INFO [FlowRuleManager] Flow rules loaded: {/T1/sentinel=[FlowRule{resource=/T1/sentinel, limitApp=default, grade=1, count=5.0, strategy=0, refResource=null, controlBehavior=0, warmUpPeriodSec=10, maxQueueingTimeMs=500, clusterMode=false, clusterConfig=null, controller=com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController@1895f7fe}]}

2、调用

使用postman调用接口:/T1/sentinel

调用如果操作限制,则抛出异常:

Blocked by Sentinel (flow limiting)

3、异常处理

异常处理由以下类控制:AbstractSentinelInterceptor,默认使用:DefaultBlockExceptionHandler

附录

参考

官网:https://sentinelguard.io/zh-cn/docs/introduction.html

启动配置:https://sentinelguard.io/zh-cn/docs/startup-configuration.html

规则配置:https://sentinelguard.io/zh-cn/docs/dynamic-rule-configuration.html

git:https://github.com/alibaba/Sentinel

Sentinel Dashboard中修改规则同步到Apollo

Sentinel Dashboard中修改规则同步到Nacos

Sentinel配置

java 复制代码
@ConfigurationProperties(
    prefix = "spring.cloud.sentinel"
)
@Validated
public class SentinelProperties {
    private boolean eager = false;
    private boolean enabled = true;
    private String blockPage;
    private Map<String, DataSourcePropertiesConfiguration> datasource;
    private Transport transport;
    private Metric metric;
    private Servlet servlet;
    private Filter filter;
    private Flow flow;
    private Log log;
    private Boolean httpMethodSpecify;
    private Boolean webContextUnify;
}    


    public static class Transport {
        private String port = "8719";
        private String dashboard = "";
        private String heartbeatIntervalMs;
        private String clientIp;
    }

    public static class Filter {
        private int order = Integer.MIN_VALUE;
        private List<String> urlPatterns = Arrays.asList("/**");
        private boolean enabled = true;
    }    

datasource

java 复制代码
public class DataSourcePropertiesConfiguration {
    private FileDataSourceProperties file;
    private NacosDataSourceProperties nacos;
    private ZookeeperDataSourceProperties zk;
    private ApolloDataSourceProperties apollo;
    private RedisDataSourceProperties redis;
    private ConsulDataSourceProperties consul;
}
java 复制代码
public class AbstractDataSourceProperties {
    private @NotEmpty String dataType = "json";
    private @NotNull RuleType ruleType;
    private String converterClass;
}    
public class NacosDataSourceProperties extends AbstractDataSourceProperties {
    private String serverAddr;
    private String username;
    private String password;
    private @NotEmpty String groupId = "DEFAULT_GROUP";
    private @NotEmpty String dataId;
    private String endpoint;
    private String namespace;
    private String accessKey;
    private String secretKey;
  }  

public enum RuleType {
    FLOW("flow", FlowRule.class),
    DEGRADE("degrade", DegradeRule.class),
    PARAM_FLOW("param-flow", ParamFlowRule.class),
    SYSTEM("system", SystemRule.class),
    AUTHORITY("authority", AuthorityRule.class),
    GW_FLOW("gw-flow", "com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule"),
    GW_API_GROUP("gw-api-group", "com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition");
}

各规则的Json格式

FlowRule

json 复制代码
{
	"grade": 0,
	"count": 0.0,
	"strategy": 0,
	"refResource": "refResource_d1adb0f536cc",
	"controlBehavior": 0,
	"warmUpPeriodSec": 0,
	"maxQueueingTimeMs": 0,
	"clusterMode": false,
	"clusterConfig": {
		"flowId": 0,
		"thresholdType": 0,
		"fallbackToLocalWhenFail": false,
		"strategy": 0,
		"sampleCount": 0,
		"windowIntervalMs": 0,
		"resourceTimeout": 0,
		"resourceTimeoutStrategy": 0,
		"acquireRefuseStrategy": 0,
		"clientOfflineTime": 0
	},
	"resource": "resource_87dcdbb0e7e4",
	"limitApp": "limitApp_ecab5e46394a"
}

DegradeRule

json 复制代码
{
  "grade": 0,
  "count": 0.00,
  "timeWindow": 0,
  "minRequestAmount": 0,
  "slowRatioThreshold": 0.00,
  "statIntervalMs": 0,
  "resource": "resource_8b836771d2a7",
  "limitApp": "limitApp_232e830b5584"
}

AuthorityRule

json 复制代码
{
  "strategy": 0,
  "resource": "resource_5740d7b5468a",
  "limitApp": "limitApp_e6f232966690"
}
public static final int AUTHORITY_WHITE = 0;
public static final int AUTHORITY_BLACK = 1;

SystemRule

json 复制代码
{
  "highestSystemLoad": 0.00,
  "highestCpuUsage": 0.00,
  "qps": 0.00,
  "avgRt": 0,
  "maxThread": 0,
  "resource": "resource_f465bfe8bd71",
  "limitApp": "limitApp_108cb5b2e198"
}

ParamFlowRule

json 复制代码
{
  "grade": 0,
  "paramIdx": 0,
  "count": 0.00,
  "controlBehavior": 0,
  "maxQueueingTimeMs": 0,
  "burstCount": 0,
  "durationInSec": 0,
  "paramFlowItemList": [
    {
      "object": "object_710e6d4acd92",
      "count": 0,
      "classType": "classType_419ab5d85a6f"
    }
  ],
  "hotItems": {},
  "clusterMode": false,
  "clusterConfig": {
    "flowId": 0,
    "thresholdType": 0,
    "fallbackToLocalWhenFail": false,
    "sampleCount": 0,
    "windowIntervalMs": 0
  },
  "resource": "resource_9a4243d72d21",
  "limitApp": "limitApp_7dc330e03e36"
}

sentinel的日志

sentinel的日志位置:${USER_HOME}\logs\csp\C:\Users\79219\logs\csp\

日志文件类型:

  • sentinel-block.log:拦截日志
  • jurassic-sample-biz-metrics.log.2024-02-04.2:监控日志
  • sentinel-record.log.2024-02-04.0:运行日志
相关推荐
Wang's Blog1 天前
Redis: Sentinel工作原理和故障迁移流程
redis·sentinel
小笨猪-2 天前
Redis-哨兵
数据库·redis·分布式·缓存·sentinel
天下蒂一厨2 天前
sentinel微服务部署
java·微服务·架构·sentinel
中间件XL3 天前
sentinel原理源码分析系列(一)-总述
sentinel·限流·熔断·分布式流控·集群流控
小韩加油呀3 天前
jenkins配置eureka、nacos发布优雅上下线服务
运维·eureka·nacos·jenkins·优雅上下线
后台技术汇3 天前
深刻理解Redis集群(下):Redis 哨兵(Sentinel)模式
数据库·redis·缓存·bootstrap·sentinel
学地理的小胖砸4 天前
【简介Sentinel-1】
信息可视化·sentinel·遥感·地理信息·遥感影像数据源
弥琉撒到我5 天前
微服务sentinel解析部署使用全流程
spring cloud·微服务·架构·sentinel
GIS工具-gistools20215 天前
使用SNAP工具处理Sentinel-1数据应注意磁盘和内存问题
sentinel·snap
弥琉撒到我6 天前
微服务nacos解析部署使用全流程
java·spring cloud·微服务·nacos