1. 启动和配置
1.1 Module
1.1.1 POM
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
1.1.2 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
management:
endpoints:
web:
exposure:
include: '*'
1.1.3 启动sentinel
java -jar sentinel-dashboard-1.7.0.jar
2. 流控规则
3. 降级规则
4. 热点key限流规则
何为热点:热点即经常访问的数据,很多时候我们希望统计或者限制某个热点数据中访问频次最高的TopN数据,并对其访问进行限流或者其它操作。
@GetMapping("/testHotKey")
@SentinelResource(value = "testHotKey",blockHandler = "dealHandler_testHotKey")
public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
@RequestParam(value = "p2",required = false) String p2){
return "------testHotKey";
}
public String dealHandler_testHotKey(String p1,String p2,BlockException exception)
{
return "-----dealHandler_testHotKey";
}
sentinel系统默认的提示:Blocked by Sentinel (flow limiting)
5. 系统规则
6. @SentinelResource
6.1 按资源名称限流 不加 /
6.2 按照Url地址限流 加 /
6.3 自定义限流处理逻辑
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handleException2")
public CommonResult customerBlockHandler()
{
return new CommonResult(200,"按客户自定义限流处理逻辑");
}
7. 服务熔断功能
@SentinelResource(value="", fallback="") 管java
@SentinelResource(value="", blockHandler="") 管sentinel控制台的配置违规
@SentinelResource(value="", fallback="",blockHandler="") 两个都配置,blockHandler优先
8. 规则持久化