官网
中文文档
官网学习
服务使用中的各种问题:
后台 + 前台8080
前提:
命令: java -jar sentinel-dashboard-1.8.6.jar
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>com.atguigu.springcloudgroupId>
<artifactId>cloud2022artifactId>
<version>1.0-SNAPSHOTversion>
parent>
<artifactId>cloudalibaba-sentinel-service8401artifactId>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>
<dependencies>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cspgroupId>
<artifactId>sentinel-datasource-nacosartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>4.6.3version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
project>
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
#Nacos服务注册中心地址
server-addr: localhost:8848
sentinel:
transport:
#配置Sentinel dashboard地址
#8080将会监控8401
dashboard: localhost:8080
#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
port: 8719
management:
endpoints:
web:
exposure:
include: '*'
package com.atguigu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: ${DATE} ${TIME}
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@SpringBootApplication
@EnableDiscoveryClient
public class SentinelMainApp8401 {
public static void main(String[] args) {
SpringApplication.run(SentinelMainApp8401.class, args);
}
}
package com.atguigu.springcloud.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/20 11:04
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@RestController
public class FlowLimitController {
@GetMapping("/testA")
public String testA() {
return "------testA";
}
@GetMapping("/testB")
public String testB() {
return "------testB";
}
}
发现空空如也,什么也没有
Sentinel采用懒加载
执行一次访问就能发现了
测试地址1: http://localhost:8401/testA
测试地址2: http://localhost:8401/testB
绿色通过
sentinel8080正在监控8401
直接->快速失败(系统默认)
表示1秒内查询1次,就可以正常访问,若超过次数1,就直接快速失败,报默认错误
测试:快速点击访问http://localhost:8401/testA
结果: Blocked by Sentinel (flow limiting)
思考: 直接调用默认报错信息,能够有自定义的后续处理?是否有fallback类似的兜底方法?
QPS和线程数的区别:
修改controller
开启两个testA,一个访问之后,另一个多次访问,发现
当关联的资源达到阈值时,就限流自己
当与A关联的B达到阈值之后,就限流A自己
B惹事,A挂了
例如:支付接口达到阈值之后,限流下订单接口,防止连坐效应
测试前不管点多快都不会出现流控
测试后,大批量线程高并发访问B,导致A失效了
多个请求调用同一个微服务
【未解决】
报错: Blocked by Sentinel (flow limiting)
源码: com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController
最怕一个系统的平时访问量是0,某1s突然10万访问
公式: 阈值除以coldFactor(冷加载因子,默认值为3),经过预热时长后才会达到阈值
官网
默认coldFactor为3,即请求 QPS 从 threshold / 3 开始,经预热时长逐渐升至设定的 QPS 阈值
限流冷启动
com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpController
WarmUp配置:
默认 coldFactor 为 3,即请求QPS从(threshold / 3) 开始,经多少预热时长才逐渐升至设定的 QPS 阈值
案例,阀值为10+预热时长设置5秒
系统初始化的阀值为10 / 3 约等于3,即阀值刚开始为3;然后过了5秒后阀值才慢慢升高恢复到10,效果为:开始访问 http://localhost:8401/testB 时每秒请求别超过10/3个才能正常访问,5秒后可以接受的请求可以达到每秒10次
多次点击,刚开始不行,后续慢慢可以
应用场景: 秒杀系统在开启的瞬间,会有很多流量上来,有可能把系统打死,预热方式就是为了保护系统,可慢慢的把流量放进来,慢慢的把阈值增长到设置的阈值
匀速排队,让请求以均匀的速度通过,阀值类型必须设成QPS,否则无效
设置含义:/testB每秒1次请求,超过的话就排队等待,等待的超时时间为20000毫秒
修改Controller的TestB
官网
源码: com.alibaba.csp.sentinel.slots.block.flow.controller.RateLimiterController
官网
慢调用比例(平均响应时间,秒级)
超出阈值且在时间窗口内通过的请求>=5
,两个条件同时满足后触发降级异常比列(秒级)
异常数(分钟级)
进一步说明
Sentinel 熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,让请求快速失败,避免影响到其它的资源而导致级联错误
当资源被降级后,在接下来的降级时间窗口之内,对该资源的调用都自动熔断(默认行为是抛出 DegradeException)
Sentinel 的断路器是没有半开状态的
半开的状态系统自动去检测是否请求有异常,没有异常就关闭断路器恢复使用;有异常则继续打开断路器不可用。
复习Hytrix
按照上述配置,1秒钟进来10个线程(大于5个)调用testD,我们希望200ms处理完本次任务,如果超过200ms还没处理完,在未来1s的时间窗口内,断路器打开(保险丝跳闸)微服务不可用,保险丝就跳闸断电了
关闭压测时访问,只点了一下并没有达到5,那就不会走降级,说明访问的接口是有问题的,报了异常出来。
按照上述配置,单独访问一次,必然来一次报错一次(int age = 10/0),调一次错一次;
开启jmeter后,直接高并发发送请求,多次调用达到我们的配置条件了。
断路器开启(保险丝跳闸),微服务不可用了,不再报错error而是服务降级了
何为热点?热点即经常访问的数据。很多时候我们希望统计某个热点数据中访问频次最高的 Top K 数据,并对其访问进行限制。比如:
热点参数限流会统计传入参数中的热点参数,并根据配置的限流阈值与模式,对包含热点参数的资源调用进行限流。热点参数限流可以看做是一种特殊的流量控制,仅对包含热点参数的资源调用生效。
Sentinel 利用 LRU 策略统计最近最常访问的热点参数,结合令牌桶算法来进行参数级别的流控。热点参数限流支持集群模式。
官方文档
兜底方法:分为系统默认和客户自定义两种
之前的case,限流出问题后,都是用sentinel系统默认的提示:Blocked by Sentinel (flow limiting)
我们能不能自定?类似hystrix,某个方法出问题了,就找对应的兜底降级方法?
结论:从 @HystrixCommand 到 @SentinelResource
源码: com.alibaba.csp.sentinel.slots.block.BlockException
controller新增代码
@GetMapping("/testHotKey")
@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
public String testHotKey(@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 exception){
//sentinel的默认提示都是Blocked by Sentinel (flow limiting)
return "-----------deal_testHotKey ┭┮﹏┭┮";
}
@SentinelResource(value = "testHotKey")
异常打到了前台用户界面(ERROR PAGE)看到,不友好@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
方法 testHotKey 里面第一个参数只要QPS超过每秒1次,马上降级处理如果参数索引0这种访问方式超过我们设置的QPS(即超过1秒),马上降级处理
限流模式只支持QPS模式,固定写死了。(这才叫热点)@SentinelResource
注解的方法参数索引,0代表第一个参数,1代表第二个参数,以此类推,单机阀值以及统计窗口时长表示在此窗口时间超过阀值就限流。上面的抓图就是第一个参数有值的话,1秒的QPS为1,超过就限流,限流后调用deal_testHotKey支持方法。
http://localhost:8401/testHotKey?p1=abc
http://localhost:8401/testHotKey?p1=abc&p2=33
http://localhost:8401/testHotKey?p2=abc
上述案例演示了第一个参数p1,当QPS超过1秒1次点击后马上被限流
特例情况: 超过1s/个后,达到阈值1马上被限流
我们期望p1参数当它是某个特殊值时,它的限流值和平时不一样
特例:假如当p1的值等于5时,它的阈值可以达到200
热点参数的注意点,参数必须是基本类型或者String
测试地址1: http://localhost:8401/testHotKey?p1=1
测试地址2:http://localhost:8401/testHotKey?p1=5
当p1等于5的时候,阈值变为200
当p1不等于5的时候,阈值就是平常的1
热点参数的注意点,参数必须是基本类型或者String
@SentinelResource
处理的是Sentinel控制台配置的违规情况,有blockHandler方法配置的兜底处理;
RuntimeException
:int age = 10/0,这个是java运行时报出的运行时异常RunTimeException,@SentinelResource不管
总结:@SentinelResource主管配置出错,运行出错该走异常走异常
官网
在没有添加配置之前
testA和testB是没有限制的
添加配置
再次访问testA和testB
一秒钟一下没问题,点多了就降级了
属于将整个系统的QPS都规定了,一旦超过这个阈值,整个系统就会触发系统保护引起降级
新增POM
<dependency>
<groupId>com.atguigu.springcloudgroupId>
<artifactId>cloud-api-commonartifactId>
<version>${project.version}version>
dependency>
没有修改
package com.atguigu.springcloud.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/20 15:03
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@RestController
public class RateLimitController {
@GetMapping("/byResource")
@SentinelResource(value = "byResource", blockHandler = "handleException")
public CommonResult byResource() {
return new CommonResult(200, "按资源名称限流测试OK", new Payment(2023L, "serial001"));
}
public CommonResult handleException(BlockException exception) {
return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用");
}
}
无修改
此时关闭服务8401
Sentinuel控制台流控规则消失了
所以流控规则是临时的
新增代码
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl() {
return new CommonResult(200, "按url限流测试OK", new Payment(2023L, "serial002"));
}
package com.atguigu.springcloud.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/20 15:03
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@RestController
public class RateLimitController {
@GetMapping("/byResource")
@SentinelResource(value = "byResource", blockHandler = "handleException")
public CommonResult byResource() {
return new CommonResult(200, "按资源名称限流测试OK", new Payment(2023L, "serial001"));
}
public CommonResult handleException(BlockException exception) {
return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用");
}
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl() {
return new CommonResult(200, "按url限流测试OK", new Payment(2023L, "serial002"));
}
}
用url配置限流会返回Sentinel自带的限流处理结果
系统默认的,没有体现我们自己的业务要求
依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观
每个业务方法都添加一个兜底的,那代码膨胀加剧
全局统一的处理方法没有体现
CustomerBlockHander类用于自定义限流处理逻辑
package com.atguigu.springcloud.myhandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.springcloud.entities.CommonResult;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/20 15:28
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
public class CustomerBlockHandler {
public static CommonResult handlerException(BlockException exception){
return new CommonResult(4444, "按客户自定义,global handlerException---------1");
}
public static CommonResult handlerException2(BlockException exception){
return new CommonResult(4444, "按客户自定义,global handlerException----------2");
}
}
新增代码
@GetMapping("/rateLimit/customerBlockHandler" )
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class ,
blockHandler = "handlerException2")
public CommonResult customerBlockHandler() {
return new CommonResult(200, "按客户自定义", new Payment(2023L, "serial003"));
}
@SentinelResource注解最主要的两个用法:限流控制和熔断降级的具体使用案例介绍完了。另外,该注解还有一些其他更精细化的配置,比如忽略某些异常的配置、默认降级函数等等,具体可见如下说明:
多说一句:所有的代码都要用try-catch-finally方式进行处理,o(╥﹏╥)o
Sentinel主要有三个核心Api:
sentinel整合ribbon+openFeign+fallback
cloudalibaba-provider-payment9003
cloudalibaba-provider-payment9004
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>com.atguigu.springcloudgroupId>
<artifactId>cloud2022artifactId>
<version>1.0-SNAPSHOTversion>
parent>
<artifactId>cloudalibaba-provider-payment9004artifactId>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>
<dependencies>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
<groupId>com.atguigu.springcloudgroupId>
<artifactId>cloud-api-commonartifactId>
<version>${project.version}version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
project>
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*'
package com.atguigu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: ${DATE} ${TIME}
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain9003.class, args);
}
}
package com.atguigu.springcloud.controller;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.HashMap;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 10:03
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@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;
}
}
cloudalibaba-consumer-nacos-order84
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>com.atguigu.springcloudgroupId>
<artifactId>cloud2022artifactId>
<version>1.0-SNAPSHOTversion>
parent>
<artifactId>cloudalibaba-consumer-nacos-order84artifactId>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>
<dependencies>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
dependency>
<dependency>
<groupId>com.atguigu.springcloudgroupId>
<artifactId>cloud-api-commonartifactId>
<version>${project.version}version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
project>
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
#配置Sentinel dashboard地址
dashboard: localhost:8080
#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
port: 8719
#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
nacos-user-service: http://nacos-payment-provider
package com.atguigu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: ${DATE} ${TIME}
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@SpringBootApplication
@EnableDiscoveryClient
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
package com.atguigu.springcloud.conifg;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 10:10
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
package com.atguigu.springcloud.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 10:11
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@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;
}
}
测试地址: http://localhost:84/consumer/fallback/1
给客户error页面,不友好
修改消费者84的Controller
public CommonResult handlerFallback(@PathVariable Long id, Throwable e) {
Payment payment = new Payment(id, "null");
return new CommonResult(444, "兜底异常handlerFallback,exception内容" + e.getMessage(), payment);
}
修改消费者84Controller
//本例是blockHandler
public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id, "null");
return new CommonResult(444, "blockHandler-sentinel限流,无此流水:blockException" + blockException.getMessage(), payment);
}
测试正确地址
测试地址: http://localhost:84/consumer/fallback/1
先访问一次正常的,让sentinel监控到
测试4
因此现在是运行时异常,没有fallback异常兜底,所以直接报error page,我们所作的熔断配置要2次以上才能生效
修改消费者84Controller
测试正确地址
测试地址: http://localhost:84/consumer/fallback/1
先访问一次正常的,让sentinel监控到
配置sentinel
测试正常地址,一秒点击一次,测试正常
测试正常,一秒点击多次,限流
测试一次Java运行时异常地址4,fallback兜底
快速测试多次Java运行时异常地址4,限流
若blockHandler和fallback都进行了配置,则被限流降级而抛出BlockException时只会进入blockHandler处理逻辑
测试正确地址
测试地址: http://localhost:84/consumer/fallback/1
先访问一次正常的,让sentinel监控到
修改84模块
84消费者调用提供者9003
Feign组件一般是消费者
新增POM
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
新增配置
#激活sentinel对Feign的支持
feign:
sentinel:
enabled: true
package com.atguigu.springcloud.service;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.stereotype.Component;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 11:16
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Component
public class PaymentFallbackService implements PaymentService{
@Override
public CommonResult<Payment> paymentSQL(Long id) {
return new CommonResult<>(444444,"服务降级返回-----------PaymentFallbackService",new Payment(id,"errorSerial"));
}
}
package com.atguigu.springcloud.service;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 11:13
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService {
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
新增代码
//==================== OpenFeign
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
return paymentService.paymentSQL(id);
}
测试83调用9003,此时故意关闭9003微服务提供者,看84消费者是否自动降级,不会被耗死
Sentinel控制台的流控规则是临时的,之前配进Sentinel的一些规则,只要我们重启微服务就没了,如果有一堆规则那就麻烦了。
一旦我们重启应用,sentinel规则将消失,生产环境需要将配置规则进行持久化
将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台的流控规则就能看到,只要Nacos里面的配置不删除,针对8401上sentinel的流控规则持续有效
新增POM,这里之前已经添加了
<dependency>
<groupId>com.alibaba.cspgroupId>
<artifactId>sentinel-datasource-nacosartifactId>
dependency>
添加Nacos数据源配置
datasource:
ds1:
nacos:
server-addr: localhost:8848
data-id: cloudalibaba-sentinel-service
group-id: DEFAULT_GROUP
data-type: json
rule-type: flow
[
{
"resource": "/rateLimit/byUrl",
"limitApp": "default",
"grade":1,
"count":1,
"strategy":0,
"controlBehavior":0,
"clusterMode": false
}
]
测试正确地址
测试地址: http://localhost:84/consumer/fallback/1
先访问一次正常的,让sentinel监控到
查看流控规则
测试正确地址
测试地址: http://localhost:84/consumer/fallback/1
先访问一次正常的,让sentinel监控到