15 Sentinel
Sentinel
分布式系统的流量防卫兵
官网:https://github.com/alibaba/sentinel
中文版:[https://github.com/alibaba/Sentinel/wiki/介绍](
下载:https://github.com/alibaba/Sentinel/releases
下载 jar 包 到本地
命令:java -jar sentinel-dashboard-1.7.1.jar
浏览器 localhost:8080
用户和密码都是 sentinel
初始化演示监控
- 新建模块cloudalibaba-sentinel-service8401
- pom
<dependencies>
<!-- SpringCloud ailibaba nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud ailibaba sentinel-datasource-nacos 持久化需要用到-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!-- SpringCloud ailibaba sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--监控-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- yml
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinal-service
cloud:
nacos:
discovery:
#Nacos服务注册中心地址(改成自己的服务器ip地址,本地用localhost)
server-addr: localhost:8848
sentinel:
transport:
#配置Sentin dashboard地址(改成自己的服务器ip地址,本地用localhost)
dashboard: localhost:8080
# 默认8719端口,假如被占用了会自动从8719端口+1进行扫描,直到找到未被占用的 端口
port: 8719
management:
endpoints:
web:
exposure:
include: '*'
- 主启动类
@EnableDiscoveryClient
@SpringBootApplication
public class MainApp8401 {
public static void main(String[] args) {
SpringApplication.run(MainApp8401.class, args);
}
}
- controller
@RestController
public class FlowLimitController {
@GetMapping("/testA")
public String testA() {
return "----testA";
}
@GetMapping("/testB")
public String testB() {
return "----testB";
}
}
测试,启动8401,然后刷新sentinel后台页面(因为sentinel采用懒加载策略,所以需要调用服务后才在后台显示)
在浏览器分别输入,然后刷新sentinel后台页面:
http://localhost:8401/testA
http://localhost:8401/testB
流控规则
流控模式:直接(默认)、关联、链路
流控模式:直接
簇点链路处指定添加:
每秒请求数超过1个就会就会直接失败 报错
阈值类型
QPS与线程数的区别
QPS是直接挡在外面,而线程数是有好多个线程在处理,放进来,如果处理不过来,就报错(关门打狗)
流控模式:关联
此时不管调用多少次A都不会限流,而此时超过1秒调用1次B,则会限流A。
使用Postman进行B的多次访问。
访问 A 发现 A 挂了
流控效果
预热 Warm up
然后输入http://localhost:8401/testA
,不停刷新,前5秒会限流,5秒后只要每秒不超过10个请求,就不会限流。
排队等待
降级规则
sentinel 1.8 之后 有了 半开状态
降级策略:RT
controlle添加
@GetMapping("/testD")
public String testD() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("testD 测试RT");
return "----testD";
}
降级策略:异常比例
修改 testD
@GetMapping("/testD")
public String testD() {
log.info("testD 异常比例");
int age = 10 / 0; //百分百出错
return "----testD";
}
处理请求出错超过0.2(20%,阈值),熔断降级,进入时间窗口期不处理请求,3秒后退出时间窗口期继续处理请求。(前提也是每秒请求数超过5个,防止不会熔断降级)
降级策略:异常数
@GetMapping("/testE")
public String testE() {
log.info("testE 测试异常数");
int age = 10 / 0;
return "----testE 测试异常数";
}
热点规则
@GetMapping("testHotKey")
@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
public String hotKey(@RequestParam(value = "p1",required = false)String p1,
@RequestParam(value = "p2",required = false)String p2){
return "-----testHotKey";
}
public String deal_testHotKey(String p1, String p2, BlockException exchange){
// sentinel的默认提示都是: Blocked by Sentinel (flow limiting)
return "-----deal_testHotKey";
}
重启8401,浏览器输入http://localhost:8401/testHotKey
,然后在后台对testHotKey进行热点规则配置。
如果每秒的访问请求带有索引为0(p1)的参数的数量超过1,进入统计窗口期,然后调用兜底方法,1秒后退出统计窗口期,继续处理请求。
http://localhost:8401/testHotKey?p1=1
http://localhost:8401/testHotKey?p1=1&p2=2
参数例外项
我们期望 p1 参数当它是某个特殊值时,他的限流和平时不一样,例如当 p1的值等于5时,它的阈值可以达到200
测试
给testHotKey方法添加int i = 1 / 0;
异常。
然后重新测试,发现兜底方法不适用于异常,有异常会直接打印到页面。
系统规则
针对整个系统的,每秒访问量超过1(阈值),限流。
@SentinelResource
按资源名称
@RestController
public class RateLimitController {
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource() {
return new CommonResult(200,"按照资源名称限流测试",new Payment(2020L,"serial001"));
}
//兜底方法
public CommonResult handleException(BlockException exception) {
return new CommonResult(444,exception.getClass().getCanonicalName() + "\t 服务不可用");
}
}
启动8401
http://localhost:8401/byResource
用资源名称进行配置兜底方法才生效。
多次刷新页面
报444
按照URL地址限流+后续处理
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl") //没有兜底方法,系统就用默认的
public CommonResult byUrl() {
return new CommonResult(200,"按照byUrl限流测试",new Payment(2020L,"serial002"));
}
根据 getmapping 的 url 来配置
客户自定义限流处理逻辑
新建myhandler.CustomerBlockHandler自定义限流处理类:
public class CustomerBlockHandler {
public static CommonResult handleException(BlockException exception){
return new CommonResult(4444,"按照客户自定义,global handlerException-----1");
}
public static CommonResult handleException2(BlockException exception){
return new CommonResult(4444,"按照客户自定义,global handlerException-----2");
}
}
在controller 中 添加自定义的兜底
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class,
blockHandler = "handleException2")
public CommonResult customerBlockHandler() {
return new CommonResult(200,"按照用户自定义",new Payment(2020L,"serial002"));
}
更多注解属性说明
服务熔断功能
Ribbon系列
配置消费提供 9003 9004
<dependencies>
<!-- SpringCloud ailibaba nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud ailibaba sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 引用自己定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--监控-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #nacos
management:
endpoints:
web:
exposure:
include: '*'
sentinel 监控 84
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback") //没有配置
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(
SERVICE_URL + "/paymentSQL/" + id,CommonResult.class,id);
if(id == 4){
throw new IllegalArgumentException("IllegalArgument,非法参数异常...");
}else if(result.getData() == null) {
throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
}
当id = 4 时 会报运行时异常
只配置fallback
修改84的CircleBreakerController类的fallback方法中的@SentinelResource注解,并在类中添加
@RequestMapping("/consumer/fallback/{id}")
//@SentinelResource(value = "fallback") //没有配置
@SentinelResource(value = "fallback",fallback ="handlerFallback") //只配置fallback(只负责业务异常)
public CommonResult<Payment> fallback(@PathVariable Long id) {
....//运行时异常
}
//fallback兜底
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult(444,"异常handlerFallback,exception内容: " + e.getMessage(), payment);
}
只配置blockHandler
修改@SentinelResource注解,并在类中添加
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback", blockHandler = "blockHandler") //只配置blockHandler(只负责sentinel控制台配置违规)
public CommonResult<Payment> fallback(@PathVariable Long id) {
....//运行时异常
}
//blockHandler兜底
public CommonResult blockHandler(@PathVariable Long id,BlockException e) {
Payment payment = new Payment(id,"null");
return new CommonResult(444,"blockHandler-sentinel 限流,BlockException: " + e.getMessage(), payment);
}
因为没配置指定fallback兜底方法,所以会直接显示错误页面,配置了blockHandler兜底方法,并且在sentinel 中配置了 服务降级的异常数 所以当sentinel配置违规会执行blockHandler兜底方法。
配置fallback和blockHandler
@SentinelResource(value = "fallback", fallback ="handlerFallback", blockHandler = "blockHandler")
在 sentinel 中设置了 阈值 qps = 1 并且 java中有运行时异常
这时候 qps 高了 到了 blockhandler处理
当@SentinelResource注解fallback和blockHandler都指定后,然后同时符合,优先执行blockHandler兜底方法。
忽略属性
exceptionsToIgnor
如果出现了异常 兜底的方法 就不管了
Feign系列
在 84 消费端加
- pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- yaml
#前面也已经添加了
#激活Sentinel对Feign的支持
feign:
sentinel:
enabled: true
- 主启动类上添加
@EnableFeignClients
(也已经添加了) - service
PaymentService接口
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService {
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
- 实现类
@Component
public class PaymentServiceImpl implements PaymentService {
@Override
public CommonResult<Payment> paymentSQL(Long id) {
return new CommonResult<>(444,"服务降级返回,---PaymentFallbackService",new Payment(id,"ErrorSerial"));
}
}
- controller
//======= OpenFeign
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult< Payment > paymentSQL(@PathVariable("id") Long id){
return paymentService.paymentSQL(id);
}
关闭9003和9004,执行@FeignClient的fallback兜底方法PaymentFallbackService。
熔断限流框架对比
持久化规则
修改8401
- pom
<!--之前添加了-->
<!-- SpringCloud ailibaba sentinel-datasource-nacos 持久化需要用到-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
- yml
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinal-service
cloud:
nacos:
discovery:
#Nacos服务注册中心地址(改成自己的服务器ip地址,本地用localhost)
server-addr: localhost:8848
sentinel:
transport:
#配置Sentin dashboard地址(改成自己的服务器ip地址,本地用localhost)
dashboard: localhost:8080
# 默认8719端口,假如被占用了会自动从8719端口+1进行扫描,直到找到未被占用的 端口
port: 8719
datasource:
ds1:
nacos:
server-addr: 10.211.55.26:8848 #nacos
dataId: ${spring.application.name}
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
management:
endpoints:
web:
exposure:
include: '*'
- 在nacos后台添加配置:将流控规则配置进nacos
停止后 重启了也还存在
实现sentinel配置的持久化。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)