一、环境准备
1、Spring Cloud中单个服务并能正常使用。参考链接
2、Sentinel已经搭建。
3、服务已经整合Sentinel参考链接
4、Nacos已经搭建。参考链接
二、Sentinel中读取Nacos中配置
1、引入依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
2、application.yml配置
server:
port: 7101
spring:
application:
name: a-server
cloud:
sentinel:
transport:
# sentinel地址
dashboard: pfhe.com:7003
# 此端口用于跟sentinel绑定,集群时能知道具体那台
port: 7200
# 程序启动就建立心跳
eager: true
datasource:
ds:
nacos:
# nacos地址
server-addr: pfhe.com:7001
# 命名空间
namespace: ${spring.profiles.active}
# Data Id
dataId: ${spring.application.name}-sentinel-flow-rules
# 分组,默认DEFAULT_GROUP
groupId: SENTINEL_GROUP
# 格式
data-type: json
# 类型
rule-type: flow
# nacos账号
username: nacos
# nacos账号的密码
password: nacos
3、Nacos中对应配置文件的内容
3.1、添加服务的Sentinel配置文件
[
{
"app": "a-server",
"clusterConfig": {
"fallbackToLocalWhenFail": true,
"sampleCount": 110,
"strategy": 0,
"thresholdType": 0,
"windowIntervalMs": 1000
},
"clusterMode": false,
"controlBehavior": 0,
"count": 6,
"gmtCreate": 1646375875441,
"gmtModified": 1646560397517,
"grade": 1,
"id": 24,
"ip": "172.22.144.1",
"limitApp": "default",
"port": 8720,
"resource": "/index",
"strategy": 0
}
]
参数解答:参考链接
resource 资源名,资源名是限流规则的作用对象
count 限流阈值
grade 限流阈值类型,QPS 或线程数模式 QPS 模式
limitApp 流控针对的调用来源,default,代表不区分调用来源
strategy 判断的根据是资源自身,还是根据其它关联资源 (refResource),还是根据链路入口 根据资源本身
controlBehavior 流控效果(直接拒绝 / 排队等待 / 慢启动模式),直接拒绝
3.2、添加网关服务的Sentinel配置
[
{
"apiName": "a-server",
"app": "gateway-server",
"gmtCreate": 1646473266000,
"gmtModified": 1646473266000,
"id": 1,
"ip": "172.22.144.1",
"port": 7201,
"predicateItems": [
{
"matchStrategy": 1,
"pattern": "/a-server"
}
]
}
]