1.sentinel的简介
官网
是什么
一句话解释,就是之前的Hystrix,负责熔断,降级,限流
去哪下
https://github.com/alibaba/Sentinel/releases
直接下载1.7版本
能干吗
怎么玩
服务中的各种问题
- 服务雪崩
- 服务降级
- 服务熔断
- 服务限流
2.sentinel控制台的安装
下载地址
https://github.com/alibaba/Sentinel/releases
下载到本地sentinel-dashboard-1.7.0.jar
运行命令
前提
java8环境OK,8080端口不能被占用,直接启动即可
java -jar sentinel-dashboard-1.7.0.jar
访问地址 http://localhost:8080 访问sentinel管理界面
登录账号密码均为sentinel
3.初始化演示工程
依赖问题 父pom是如下
<!--spring cloud alibaba 2.1.0.RELEASE-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
启动Nacos8848成功
http://localhost:8848/nacos/#/login
创建新模块cloudalibaba-sentinel-service8401
pom
<dependencies>
<dependency>
<groupId>com.chl.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--sentinel和nacos的整合 将sentinel的数据存到nocas-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!--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>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.3</version>
</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-sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848 #注册到nacos
sentinel:
transport:
dashboard: localhost:8080 #sentinal的控制面板
port: 8719 #默认8719,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口
#暴露这个,被监控
management:
endpoints:
web:
exposure:
include: '*'
主启动
@EnableDiscoveryClient
@SpringBootApplication
public class MainApp8401{
public static void main(String[] args) {
SpringApplication.run(MainApp8401.class, args);
}
}
业务类
@RestController
public class FlowLimitController{
@GetMapping("/testA")
public String testA() {
return "------testA";
}
@GetMapping("/testB")
public String testB() {
return "------testB";
}
}
启动Sentinel8080
java -jar sentinel-dashboard-1.7.0
启动微服务8401
启动8401微服务后查看sentienl控制台,会发现控制台什么都没有空空如也,啥都没有
Sentinel采用的懒加载说明
需要你访问这个才会出现,所以执行一次访问即可
- http://localhost:8401/testA
- http://localhost:8401/testB
所以结论就是,sentinel8080正在监控微服务8401
常见添加配置操作
一般切到列表视图,方便查看 ,显示的访问的 url
可以对url进行相应的配置
4.流控规则
基本介绍
- 也可以在族点链路,对链路添加配置
- 可以在流控规则上面添加配置
GPS和线程数的区别
- QPS是请求接受前(拒之门外)
- 线程数就是接受了这个请求(关门打狗)
流控模式
直接(默认)
系统默认就是直接失败
快速点击访问 http://localhost:8401/testA
接着页面显示 Blocked by Sentinel (flow limiting)
思考
- 直接调用默认报错信息,技术方面OK but,是否应该有我们自己的后续处理?
- 类似有一个hystrix的fallback的兜底方法?
关联
- 当关联的资源达到阈值时,就限流自己
- 当与A(订单模块)关联的资源B(支付模块)达到阈值后,就限流自己
- 就好比如我的支付模块处理不过来了,就限流订单模块,不让继续下单
配置
测试
postman模拟并发密集访问testB
单纯访问成功 /testB
postman里新建多线程集合组
将 /testB的 url添加进线程组
接着启动线程组
postMan 线程组运行期间,接着去访问testA http://localhost:8401/testA, 发现testA挂了
页面结果 Blocked by Sentinel (flow limiting)
结论 大批量线程高并发访问B,导致A失效了
链路 (待补充)
多个请求调用了同一个微服务
流控效果
直接->快速失败(默认的流控处理)
直接失败,抛出异常,Blocked by Sentinel (flow limiting)
源码相应的类如下:
com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController
预热
基本介绍
就是平时不怎么访问的资源,例如,秒杀的东西,突然急剧上升,用预热搞得让进来的请求慢慢的处理完,而不是一下子请求这么多导致系统崩溃
公式:阈值除以coldFactor(默认值为3),经过预热时长后才会达到阈值
默认coldFactor为3,即请求QPS从threshold/3开始,经预热时长逐渐升至设定的QPS阈值。
官网
官网链接 限流 冷启动
https://github.com/alibaba/Sentinel/wiki/限流---冷启动
源码
com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpController
wakeup配置
测试
多次点击http://localhost:8401/testB
刚开始不行,后续慢慢OK
应用场景
排队等待
基本介绍
匀速排队,阈值必须设置为QPS
官网
源码
com.alibaba.csp.sentinel.slots.block.flow.controller.RateLimiterController
配置
测试
用postman测试,1秒一个
看后台,打印的匀速测试,1秒通过一个
5.降级规则
基本介绍
这三个降级规则条件满足,都是两个条件,并列条件,都满足才会触发
RT (平均相应时间,秒级)
在cloudalibaba-sentinel-service8401 添加一个测试方法
@GetMapping("/testD")
public String testD() {
//测试RT 平均响应时间 ,如果这么多个请求,你的响应时间都大于设置的平均响应时间
//就降级
try {
TimeUnit.SECONDS.sleep(1); //睡一秒
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("testD 测试RT");
return "------testD";
}
配置
测试
接着jmeter压测,一秒发10个请求访问 testD
异常比例
在cloudalibaba-sentinel-service8401 添加一个测试方法
@GetMapping("/testD")
public String testD() {
//测试异常比例
int i = 1/0;
log.info("testD 测试异常比例");
return "------testD";
}
配置
测试
jmeter压测
结果
异常数
异常数是按照分钟统计的
//testE 测试异常数
@GetMapping("/testE")
public String testE() {
log.info("testE 测试异常数");
int age = 10/0;
return "------testE 测试异常数";
}
配置
测试
直接浏览器,访问成功,点多几次就不报错了,直接跳sentinel的 Blocked by Sentinel (flow limiting)
6.热点key限流
官网
https://github.com/alibaba/Sentinel/wiki/热点参数限流
本次案例用一下 @SentinelResource
不符合配置规则的异常 com.alibaba.csp.sentinel.slots.block.BlockException
在cloudalibaba-sentinel-service8401 添加一个测试方法
//热点key测试
@GetMapping("/testHotKey")
//这里的value,就是热点规则,配置的资源名
@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
@RequestParam(value = "p2",required = false) String p2) {
//int age = 10/0;
return "------testHotKey";
}
//兜底方法
public String deal_testHotKey (String p1, String p2, BlockException exception){
return "------deal_testHotKey,o(╥﹏╥)o";
}
配置
这里我们直接添加资源名的限流规则
资源名和默认的url区别
- 资源名就是@SentinelResource,设置的value值,是没有 / 的,这个才能配置走我们自定义的
- 而默认的url,是有 / 的 url方式走不了自定义兜底
参数索引说明
// 从0 开始 即p1 是索引是0 , p2 是索引是1
@RequestParam(value = "p1",required = false) String p1,
@RequestParam(value = "p2",required = false) String p2
就是带有第一个参数 p1 访问的就限流
http://localhost:8401/testHotKey?p1=abc //限流
http://localhost:8401/testHotKey?p1=abc&p2=33 //限流
http://localhost:8401/testHotKey?p2=abc //不限流
测试
@SentinelResource(value = "testHotKey")
没有配置自定义的blockBack,返回的是Blocked by Sentinel (flow limiting)
@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
方法testHostKey里面第一个参数只要QPS超过每秒1次,马上降级处理,配置了blockBack,走自定义的blockBack
参数例外项
特殊情况说明
上述案例演示了第一个参数p1,当QPS超过1秒1次点击后马上被限流
- 超过1秒钟一个后,达到阈值1后马上被限流
- 我们期望p1参数当它是某个特殊值时,它的限流值和平时不一样
- 假如当p1的值等于5时,它的阈值可以达到200
配置
写好参数值等相应参数,就点击添加按钮
测试
疯狂访问这个
http://localhost:8401/testHotKey?p1=5 //不限流 当p1等于5的时候,阈值变为200
http://localhost:8401/testHotKey?p1=3 //被限流 当p1不等于5的时候,阈值就是平常的1
热点参数的注意点,参数必须是基本类型或者String
其他
手贱添加异常看看.... 异常的兜底后面讲
7.系统规则
就是整体的全部 的相应配置 统一配置的意思 这个还是少用
可以配置全局QPS 来玩下
8.@SentinelResource
按资源名称限流+后续处理
启动Nacos成功,启动Sentinel成功
在cloudalibaba-sentinel-service8401
pom
<dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<groupId>com.chl.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
yml
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848 #注册到nacos
sentinel:
transport:
dashboard: localhost:8080 #sentinal的控制面板
port: 8719 #默认8719,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口
#暴露这个,被监控
management:
endpoints:
web:
exposure:
include: '*'
业务类
@RestController
@Slf4j
public class FlowLimitController {
//测试资源名 走自定义兜底方法
//测试兜底的方法
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource() {
return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));
}
public CommonResult handleException(BlockException exception) {
return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服务不可用");
}
}
配置
图形配置和代码关系:
表示1秒钟内查询次数大于1,就跑到我们自定义的处流,限流
测试
- 1秒钟点击1下,OK
- 超过上述问题,疯狂点击,返回了自己定义的限流处理信息,限流发送
额外问题
此时关闭微服务8401看看,Sentinel控制台,流控规则消失了????? 临时/持久?
所以就是临时的
按照Url地址限流+后续处理
通过访问的URL来限流,会返回Sentinel自带默认的限流处理信息
添加测试代码
//测试url 走的默认兜底方法
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl() {
return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
}
访问一次这个链接,控制台就出现了
配置
测试
疯狂点击http://localhost:8401/rateLimit/byUrl
上面兜底方法面临的问题
客户自定义限流处理逻辑
创建customerBlockHandler类用于自定义限流处理逻辑
自定义限流处理类
//自定义兜底的方法 要写静态的
public class CustomerBlockHandler {
//兜底方法1
public static CommonResult handleException(BlockException exception) {
return new CommonResult(2020, "自定义限流处理信息....CustomerBlockHandler");
}
//兜底方法2
public static CommonResult handlerException2(BlockException exception) {
return new CommonResult(2020, "自定义限流处理信息....CustomerBlockHandler2");
}
}
在RateLimitController添加测试方法
//测试走用户自定义限流的 ,实现代码也业务类分离
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class, //兜底的类
blockHandler = "handlerException2") //兜底的哪个方法
public CommonResult customerBlockHandler() {
return new CommonResult(200,"按客戶自定义",new Payment(2020L,"serial003"));
}
启动微服务后先调用一次
http://localhost:8401/rateLimit/customerBlockHandler
配置
直接设置普通的限流 阀值 1
测试
我们自定义的出来了,访问我们自定义的兜底类,和相应的兜底方法
进一步说明
更多注解属性说明
Java代码形式配置(了解即可)
Sentinel主要有三个核心API
- SphU定义资源
- Tracer定义统计
- ContextUtil定义了上下文
9.服务熔断
整合ribbon
启动nacos和sentinel
新建模块cloudalibaba-provider-payment9003/9004
pom
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<groupId>com.chl.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- SpringBoot整合Web组件 -->
<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>
<!--日常通用jar包配置-->
<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: #记得修改不同的端口号 9003 / 9004
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
#暴露端口被监控
management:
endpoints:
web:
exposure:
include: '*'
主启动
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain9003.class, args);
}
}
业务类
@RestController
public class PaymentController {
@Value("${server.port}")
private String serverPort;
public static HashMap<Long, Payment> hashMap = new HashMap<>();
static{
hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));
hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));
hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));
}
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
Payment payment = hashMap.get(id);
CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort: "+serverPort,payment);
return result;
}
}
测试地址
http://localhost:9003/paymentSQL/1
http://localhost:9004/paymentSQL/1
新建cloudalibaba-consumer-nacos-order84
pom
<dependencies>
<!--open feign的依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--setinel监控-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.chl.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</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: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos: #注册进nacos
discovery:
server-addr: localhost:8848
sentinel:
transport: #受sentinel的监控
dashboard: localhost:8080
port: 8719
service-url:
nacos-user-service: http://nacos-payment-provider
#暴露这个,被监控
management:
endpoints:
web:
exposure:
include: '*'
启动类
@EnableDiscoveryClient
@SpringBootApplication
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
业务类
ribbon,要使用restTemplate
@Configuration
public class ApplicationContextConfig {
//注入restTemplate
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
CircleBreakerController
@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") //没有配置
//单单测试异常兜底 fallback
//@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback只负责业务异常
//单单测试限流兜底 blockHandler
//@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
//同时测试 fallback blockHandler
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",
exceptionsToIgnore = {IllegalArgumentException.class} //测试哪个异常排除,不走异常兜底的方法
)
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 ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
//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 处理降级的 兜底
public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
}
}
热部署对java代码级生效及时,对@SentinelResource注解内属性,有时效果不好
修改@SentinelResource后,请重启微服务
fallBack和blockHandler
- fallback管运行异常
- blockHandler管配置违规
测试地址
http://localhost:84/consumer/fallback/1
测试
没有任何配置
给客户error页面,不友好
@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 ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
}
只配置fallback
出现异常,走异常的兜底
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
//单单测试异常兜底 fallback
@SentinelResource(value = "fallback",fallback = "handlerFallback") //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 ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
//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
服务降级,走降级的兜底
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
//单单测试限流兜底 blockHandler
//@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
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 ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
//blockHandler 处理降级的 兜底
public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
}
}
fallback和blockHandler都配置
- 正常符合限流规则的访问,走异常的兜底
- 当不符合限流的配置,就走限流的兜底
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
//同时测试 fallback blockHandler
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler")
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 ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
//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 处理降级的 兜底
public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
}
}
忽略属性
就是哪个异常不走异常兜底 方便排查错误
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
//同时测试 fallback blockHandler
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",
exceptionsToIgnore = {IllegalArgumentException.class} //测试哪个异常排除,不走异常兜底的方法
)
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 ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
//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 处理降级的 兜底
public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
}
}
整合openFeign
修改cloudalibaba-consumer-nacos-order84 模块
pom 添加openFeign的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
yml 打开对Feign的支持
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos: #注册进nacos
discovery:
server-addr: localhost:8848
sentinel:
transport: #受sentinel的监控
dashboard: localhost:8080
port: 8719
service-url:
nacos-user-service: http://nacos-payment-provider
#暴露这个,被监控
management:
endpoints:
web:
exposure:
include: '*'
#对Feign的支持
feign:
sentinel:
enabled: true
业务类
新建立feign的接口 PaymentService 并指定兜底的类
// feigin 指定哪个微服务
// fallback 执行feign 式的fallback
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService {
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
实现PaymentService 用于 对feign接口调用的统一兜底方法
//实现feign的接口,来自定义兜底
@Component
public class PaymentFallbackService implements PaymentService {
@Override
public CommonResult<Payment> paymentSQL(Long id) {
return new CommonResult<>(44444,"服务降级返回,---PaymentFallbackService",new Payment(id,"errorSerial"));
}
}
在CircleBreakerController,添加测试方法
// 测试和 OpenFeign 的整合 和openfeign整合的fallback
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
return paymentService.paymentSQL(id);
}
启动类
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients //开启openfeign
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
测试
http://lcoalhost:84/consumer/paymentSQL/1
测试84调用9003,此时故意关闭9003微服务提供者,看84消费侧自动降级,不会被耗死
熔断框架的比较
10.规则持久化
一旦我们重启应用,Sentinel规则将消失,生产环境需要将配置规则进行持久化
官网建议我们将限流配置规则持久化进Nacos保存
只要刷新8401某个rest地址,sentinel控制台的流控规则就能看到,只要Nacos里面的配置不删除,针对8401上Sentinel上的流控规则持续有效
修改cloudalibaba-sentinel-service8401
pom
<!--sentinel和nacos的整合 将sentinel的数据存到nocas-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
yml
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848 #注册到nacos
sentinel:
transport:
dashboard: localhost:8080 #sentinal的控制面板
port: 8719 #默认8719,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口
datasource: #这个是将就是 sentinel 将规则持久化到 nacos 的配置
ds1:
nacos: #将这个微服务的限流存到 nacos的这个配置文件
server-addr: localhost:8848
dataId: cloudalibaba-sentinel-service #创建的dataId
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
#暴露这个,被监控
management:
endpoints:
web:
exposure:
include: '*'
将业务规则配置添加进nacos的配置
内容解析
[
{
"resource": "/retaLimit/byUrl",
"limitApp": "default",
"grade": 1,
"count": 1,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
启动8401后,接着访问一下接口
刷新sentinel发现业务规则有了
测试
http://localhost:8401/rateLimit/byUrl 快速访问测试接口
停止8401再看sentinel
重新启动8401再看sentinel
扎一看还是没有,稍等一会儿
http://localhost:8401/rateLimit/byUrl 多次调用
重新配置出现了,持久化验证通过