服务限流不仅仅只是针对某个服务中的接口进行限流,同一秒钟内一个人访问一个系统,那么会有多个http请求过来,我们不可能给每个接口都去加一个限流,所以我们的限流就应该是在网关层面做:
1.先对整个模块进行限流
2.然后再对这个模块中的某个接口进行限流
第一步导入依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- SpringCloud Alibaba Sentinel Gateway -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<!-- Sentinel Datasource Nacos这个是把我们的配置持久化到我们的nacos,而nacos又把数据存到数据库 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
第二步下载sentinel服务端:https://github.com/alibaba/Sentinel/releases
运行命令:nohup java -Dserver.port=9207 -Dcsp.sentinel.dashboard.server=localhost:9207 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.0.jar &
第三部配置yml:
# 全局限流
sentinel:
transport:
#这个端口是sentinel和微服务通信的端口不用管
port: 8719
#此处的地址为自己安装的服务器地址
dashboard: 127.0.0.1:9207
#这个配置是用来数据持久化的
datasource:
flow:
nacos:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
data-id: sentinel-ruoyi-gateway
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow # 类型来自RuleType类
第四部要注意了-一定是在nacos的public空间下中创建格式text
[
{
"resource": "微服务模块1",
"count": 2000,
"grade": 1,
"limitApp": "default",
"strategy": 0,
"controlBehavior": 0
},
{
"resource": "微服务模块2",
"count": 4000,
"grade": 1,
"limitApp": "default",
"strategy": 0,
"controlBehavior": 0
}
]
好了现在比如说你在微服务2模块中有一个接口需要单独控流那么加上一个类
@Configuration
public class GatewayConfiguration {
@PostConstruct
public void doInit() {
initCustomizedApis();
initGatewayRules();
}
private void initCustomizedApis() {
Set<ApiDefinition> definitions = new HashSet<>();
ApiDefinition api1 = new ApiDefinition("self_api_group1")
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
add(new ApiPathPredicateItem().setPattern("/url/1111"));
}});
definitions.add(api1);
ApiDefinition api2 = new ApiDefinition("self_api_group2")
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
add(new ApiPathPredicateItem().setPattern("/url/22222"));
}});
definitions.add(api2);
GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}
private void initGatewayRules() {
Set<GatewayFlowRule> rules = new HashSet<>();
rules.add(new GatewayFlowRule("self_api_group1")
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
.setCount(1000)//限流数
.setIntervalSec(1)
.setGrade(1)
.setControlBehavior(0)
);
rules.add(new GatewayFlowRule("self_api_group2")
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
.setCount(70)//限流数
.setIntervalSec(1)
.setGrade(1)
.setControlBehavior(0)
);
GatewayRuleManager.loadRules(rules);
}