为了防止单点故障和服务雪崩,微服务架构中需要有容错机制,以便服务调用失败时可以快速返回,以防止系统崩溃,保证高可用。这种容错机制就是由“断路器”组件实现的。
在使用Spring Cloud Netflix
时,我们一般使用Hystrix
作为断路器。而Spring Cloud Alibaba
则提供了更好的选择——Sentinel
。
首先,下载Sentinel Dashboard
并编译、启动:
https://github.com/alibaba/Sentinel/tree/master/sentinel-dashboard
在wendev-consumer
的pom.xml
中添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel</artifactId>
</dependency>
在application.yml中打开Sentinel:
spring:
application:
name: wendev-consumer
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
sentinel:
transport:
dashboard: 127.0.0.1:8080
enabled: true
eager: true
注意spring.cloud.sentinel
节点。
然后在site.wendev.microservice.consumer
包下新建一个exception
包,新建一个ExceptionHandler
类,用来编写断路器被打开时的处理逻辑。
ExceptionHandler.java
public class ExceptionHandler {
public static String blockExceptionHandle(String message, BlockException exception) {
return String.format("Welcome to WenDev, your message is %s but request bad.", message);
}
}
然后在需要开启断路器的资源上加上@SentinelResource
注解,并将刚才写的ExceptionHandler
类配置进去:
@RestController
public class MainController {
@Reference
private HelloService helloService;
@SentinelResource(value = "hello", entryType = EntryType.OUT,
blockHandlerClass = ExceptionHandler.class, blockHandler = "blockExceptionHandle")
@GetMapping(value = "/hello/{message}")
public String sayHello(@PathVariable(value = "message") String message) {
return helloService.hello(message);
}
}
其中blockHandlerClass
是我们刚才写的类,blockHandler
是类中的blockExceptionHandle
方法。
打开Sentinel Dashboard
,默认用户名和密码都是sentinel,添加一个流控规则:
“资源名”就是刚才配置的注解中“value”的值。
快速刷新,可以发现断路器被成功触发了:
网友评论