Spring Cloud Sentinel 2
续上文:https://blog.csdn.net/BogerPeng/article/details/123919758
9. 服务熔断功能
sentinel整合ribbon+openFeign+fallback
9.1 启动nacos和sentinel
9.2 provider 9003 和 9004
9.2.1 pom.xml
<dependencies>
<!-- SpringCloud Alibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</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>com.pyh.springcloud</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</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>
</dependencies>
9.2.2 yaml
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
#server-addr: 192.168.226.128:8848 # 配置 nacos 地址
# 换成 nginx 的 1111 端口 nginx - keepalived - nacos
server-addr: 192.168.226.129:1111
endpoints:
web:
exposure:
include: "*" # 暴露监控端点
9.2.3 主启动类
@SpringBootApplication
@EnableDiscoveryClient
public class NacosPaymentMain9003 {
public static void main(String[] args) {
SpringApplication.run(NacosPaymentMain9003.class,args);
}
}
9.2.4 controller
@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,"XXXXXX324235281"));
hashMap.put(2L, new Payment(2L,"XXXXXX324235282"));
hashMap.put(3L, new Payment(3L,"XXXXXX324235283"));
}
@GetMapping("/paymentSQL/{id}")
public CommonResult getPayment(@PathVariable("id") Long id){
Payment payment = hashMap.get(id);
CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort:"+serverPort,payment);
return result;
}
}
9.2.5 9004 从9003 拷贝而来
9.3 consumer端 84
9.3.1 pom
<dependencies>
<!-- SpringCloud Alibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- springcloud alibaba sentinel-datasource-nacos 后续作持久化用到-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!-- springcloud alibaba sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- openfeign -->
<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>com.pyh.springcloud</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</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>
</dependencies>
9.3.2 yaml
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
#server-addr: 192.168.226.128:8848 # 配置 nacos 地址
# 换成 nginx 的 1111 端口 nginx - keepalived - nacos
server-addr: 192.168.226.129:1111
sentinel:
transport:
# Sentinel dashboard 地址
dashboard: 192.168.226.128:8080
# 默认 8719 端口,假如被占用,会自动从8719开始依次+1扫描,直到找到未被占用的端口
port: 8719
management:
endpoints:
web:
exposure:
include: "*" # 暴露监控端点
# 消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者), 可以在程序运行时@Value来调用
service-url:
nacos-user-service: http://nacos-payment-provider
9.3.3 主启动类
@SpringBootApplication
@EnableDiscoveryClient
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class,args);
}
}
9.3.4 配置类
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
9.3.5 controller
@RestController
public class CircuitBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
// 测试不同情况下的相应结果
@RequestMapping("/consumer/fallback/{id}")
//@SentinelResource(value = "fallback") //没有配置
//@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback只负责业务异常
//@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
@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);
}
}
这里配置了多种情况下的 @SentinelResource
//没有配置
@SentinelResource(value = "fallback")
//fallback只负责业务异常
@SentinelResource(value = "fallback",fallback = "handlerFallback")
//blockHandler只负责sentinel控制台配置违规
@SentinelResource(value = "fallback",blockHandler = "blockHandler")
//包含了业务异常和Sentinel控制台配置违规。
// 如果同时发生异常和控制台违规,会优先处理违规,然后才是异常信息。
// 因为控制流量在外,逻辑异常在内
// exceptionsToIgnore 是指兜底方法handlerFallback不会兜底其指定的异常,异常会直接返回前端
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",exceptionsToIgnore = {IllegalArgumentException.class})
10. Sentinel + OpenFeign
10.1 OpenFeign 配置
配置module: cloudalibaba-consumer-nacos-order-84
10.1.1 pom
<!--SpringCLoud OpenFeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
10.1.2 yaml
# 激活 Sentinel 对 Feign 的支持
feign:
sentinel:
enabled: true
10.1.3 主启动类
添加 @EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class,args);
}
}
10.1.4 service
使用openfeign调用nacos-payment-provider 的方法
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService {
@GetMapping("/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
并通过 fallback = PaymentFallbackService.class 设置兜底类
@Component
public class PaymentFallbackService implements PaymentService{
@Override
public CommonResult<Payment> paymentSQL(Long id) {
return new CommonResult<>(444,"服务降级返回,----PaymentFallbackService",new Payment(id,"error Serial"));
}
}
10.1.5 controller
/// ================ OpenFeign
// 在 CircuitBreakerController 添加以下内容
@Resource
private PaymentService paymentService;
@GetMapping("/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
return paymentService.paymentSQL(id);
}
10.1.6 测试
开启 84 、 9003 、 9004
URL: http://localhost:84/consumer/paymentSQL/1
Response1:
{"code":200,"message":"from mysql,serverPort:9004","data":{"id":1,"serial":"XXXXXX324235281"}}
Response2:
{"code":200,"message":"from mysql,serverPort:9003","data":{"id":1,"serial":"XXXXXX324235281"}}
此时关闭 9003, 那么只会显示 9004 的调用结果
如果再关闭9004, 那么返回之前配置的兜底错误信息
{"code":444,"message":"服务降级返回,----PaymentFallbackService","data":{"id":1,"serial":"error Serial"}}
11. 熔断框架比较
12. Sentinel 持久化
12.1 新增内容
在 module: cloudalibaba-sentinel-service8403
把Sentinel 经由 nacos 配置到数据库进行持久化
12.1.1 pom文件
<!-- springcloud alibaba sentinel-datasource-nacos 后续作持久化用到-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
12.1.2 yaml
添加nacos数据源配置
spring:
cloud:
sentinel:
datasource:
ds1:
nacos:
#server-addr: 192.168.226.128:8848 # 配置 nacos 地址
# 换成 nginx 的 1111 端口 nginx - keepalived - nacos
server-addr: 192.168.226.129:1111
dataId: cloudalibaba-sentinel-service # 当前微服务名称
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
12.2 去nacos 新建配置
[
{
"resource": "/rateLimit/byUrl",
"limitApp": "default",
"grade": 1,
"count": 1,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
此时启动 cloudalibaba-sentinel-service8403, 刷新sentinel,
并调用一次接口,则可以看到规则出现了, 且生效
12.3 验证
此时关闭8403, 发现 Sentinei规则没有了。
再重新启动8403,并刷新一下url,则规则重新出现。
说明规则持久化成功