sentinel 流控规则持久化

1,156 阅读4分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

1. 在项目 pom.xml 文件中加入 sentinel-datasource-nacos 依赖
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

sentinel-datasource-nacos 是 Sentinel 为 Nacos 扩展的数据源模块,允许将规则数据存储在 Nacos 配置中心,在微服务启动时利用该模块 Sentinel 会自动在 Nacos下载对应的规则数据。

2. 在application.yml 文件中增加 Nacos下载规则
#spring:
#  application:
#    name: sentinel-sample #应用名&微服务id
#  cloud:
#    sentinel: #Sentinel Dashboard通信地址
#      transport:
#        dashboard: 10.173.203.14:9100
#      eager: true #取消控制台懒加载
#    nacos: #Nacos通信地址
#      server-addr: 10.173.203.14:8848
#      username: nacos
#      password: nacos
#server:
#  port: 80
#management:
#  endpoints:
#    web: #将所有可用的监控指标项对外暴露
#      exposure: #可以访问 /actuator/sentinel进行查看Sentinel监控项
#        include: '*'

spring:

  application:

    name: sentinel-sample #应用名&微服务id

  cloud:

    sentinel: #Sentinel Dashboard通信地址

      transport:

        dashboard: 10.173.203.158:8080

      eager: true #取消控制台懒加载

      datasource:

        flow: #数据源名称,可以自定义

          nacos: #nacos配置中心

            #Nacos内置配置中心,因此重用即可

            server-addr: ${spring.cloud.nacos.server-addr}

            dataId: ${spring.application.name}-flow-rules #定义流控规则data-id,完整名称为:sentinel-sample-flow-rules,在配置中心设置时data-id必须对应。

            groupId: SAMPLE_GROUP #gourpId对应配置文件分组,对应配置中心groups项

            rule-type: flow #flow固定写死,说明这个配置是流控规则 degrade

            username: nacos #nacos通信的用户名与密码

            password: nacos

    nacos: #Nacos通信地址

      server-addr: 10.173.203.14:8848

      username: nacos

      password: nacos

  jackson:
    default-property-inclusion: non_null

server:
  port: 80

management:
  endpoints:
    web: #将所有可用的监控指标项对外暴露
      exposure: #可以访问 /actuator/sentinel进行查看Sentinel监控项
        include: '*'
logging:
  level:
    root: debug #开启 debug 是学习需要,生产改为 info 即可
3. 在 Nacos 配置中心页面,新增 data-id 为sentinel-sample-flow-rules 的配置项。

这里 data-id 与 groups 与微服务应用的配置保持对应,最核心的配置内容采用 JSON 格式进行书写,我们来分析下这段流控规则。

[

    {

        "resource":"/test_flow_rule", #资源名,说明对那个URI进行流控

        "limitApp":"default",  #命名空间,默认default

        "grade":1, #类型 0-线程 1-QPS

        "count":2, #超过2个QPS限流将被限流

        "strategy":0, #限流策略: 0-直接 1-关联 2-链路

        "controlBehavior":0, #控制行为: 0-快速失败 1-WarmUp 2-排队等待

        "clusterMode":false #是否集群模式

    }

]

可以参考: Sentinel 的 GitHub 文档进行学习。

github.com/alibaba/Sen…

4. 查看服务的流量控制规则

访问 : http://localhost/actuator/sentinel 在 flowRules 这个数组中,可以看到 对应流控规则

{
	"appName": "sentinel-sample",
	"consoleServer": [{
		"r1": "10.173.203.158",
		"r2": 8080
	}],
	"coldFactor": "3",
	"rules": {
		"systemRules": [],
		"authorityRule": [],
		"paramFlowRule": [],
		"flowRules": [{
			"resource": "/test_flow_rule",
			"limitApp": "default",
			"grade": 1,
			"count": 1.0,
			"strategy": 0,
			"controlBehavior": 0,
			"warmUpPeriodSec": 10,
			"maxQueueingTimeMs": 500,
			"clusterMode": false,
			"clusterConfig": {
				"thresholdType": 0,
				"fallbackToLocalWhenFail": true,
				"strategy": 0,
				"sampleCount": 10,
				"windowIntervalMs": 1000
			}
		}],
		"degradeRules": []
	},
	"metricsFileCharset": "UTF-8",
	"filter": {
		"order": -2147483648,
		"urlPatterns": ["/**"],
		"enabled": true
	},
	"totalMetricsFileCount": 6,
	"datasource": {
		"flow": {
			"nacos": {
				"dataType": "json",
				"ruleType": "FLOW",
				"serverAddr": "10.173.203.14:8848",
				"username": "nacos",
				"password": "nacos",
				"groupId": "SAMPLE_GROUP",
				"dataId": "sentinel-sample-flow-rules"
			}
		}
	},
	"clientIp": "10.173.134.200",
	"clientPort": "8719",
	"logUsePid": false,
	"metricsFileSize": 52428800,
	"logDir": "C:\\Users\\xulihui\\logs\\csp\\",
	"heartbeatIntervalMs": 10000
}
5. 自定义资源点进行熔断保护

在 sentinel-core 客户端中为开发者提供了 @SentinelResource 注解,该注解允许在程序代码中自定义 Sentinel 资源点来实现对特定方法的保护

在 sentinel-core 中基于 Spring AOP(面向切面技术)可在目标 Service 方法执行前按熔断规则进行检查,只允许有效的数据被送入目标方法进行处理。

5.1 声明切面
 // 注解支持的配置Bean
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
5.2 声明资源点

在 SampleService.createOrder 方法上增加 @SentinelResource 注解用于声明 Sentinel 资源点,只有声明了资源点,Sentinel 才能实施限流熔断等保护措施。

/**

 * 演示用的业务逻辑类

 */

@Service

public class SampleService {

    //资源点名称为createOrder

    @SentinelResource("createOrder")

    /**

     * 模拟创建订单业务

     * 抛出IllegalStateException异常用于模拟业务逻辑执行失败的情况

     */

    public void createOrder() throws IllegalStateException{

        try {

            //模拟处理业务逻辑需要101毫秒

            Thread.sleep(101);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println("订单已创建");

    }

}

5.3 获取熔断规则

打开sentinel-sample 工程的 application.yml 文件,将服务接入 Nacos 配置中心的参数以获取熔断规则。

datasource:

  flow: #之前的流控规则,直接忽略

    ...

  degrade: #熔断规则

    nacos:

      server-addr: ${spring.cloud.nacos.server-addr}

      dataId: ${spring.application.name}-degrade-rules

      groupId: SAMPLE_GROUP

      rule-type: degrade #代表熔断

     username: nacos

     password: nacos

5.4 在 Nacos 配置熔断规则

设置 data-id 为 sentinel-sample-degrade-rules,Groups 为 SAMPLE_GROUP与微服务的设置保持一致。

[{

    "resource": "createOrder", #自定义资源名

    "limitApp": "default", #命名空间

    "grade": 0, #0-慢调用比例 1-异常比例 2-异常数

    "count": 100, #最大RT 100毫秒执行时间

    "timeWindow": 5, #时间窗口5"minRequestAmount": 1, #最小请求数

    "slowRatioThreshold": 0.1 #比例阈值

}]

JSON 完整的含义是:在过去 1 秒内,如果 createOrder资源被访问 1 次后便开启熔断检查,如果其中有 10% 的访问处理时间超过 100 毫秒,则触发熔断 5 秒钟,这期间访问该方法所有请求都将直接抛出 DegradeException,5 秒后该资源点回到“半开”状态等待新的访问,如果下一次访问处理成功,资源点恢复正常状态,如果下一次处理失败,则继续熔断 5 秒钟。