什么是Resilience 4j ?
当应用程序通过网络进行通信时,会有很多出错的情况。由于连接断开,网络故障,上游服务不可用等,操作可能会超时或失败。应用程序可能会相互过载,无响应甚至崩溃。
Resilience 4j是一个Java库,可以帮助我们构建弹性和容错的应用程序。它提供了一个框架,可编写代码以防止和处理此类问题。
Resilience 4j包含众多模块,如:重试,断路器,限速器,执行时间限制器,隔舱等。可以有选择的使用其中某些功能而无需引入全部的Resilience 4j组件。
Resilience 4j可以通过Java API或者注解来使用,Spring Cloud通过Spring Cloud Circuit Breaker项目进行了集成,但是只能基于Java API来使用,依赖传递导入的Resilience4j-Spring可以以注解的方式使用Resilience 4j。
代码运行时会根据注解生成切面,切面的顺序与注解顺序无关,切面的顺序可以通过配置项调整,默认顺序如下:
Retry(CircuitBreaker(RateLimiter(TimeLimeter(Bulkhead(Dunction)))))
注意:Resilience 4j通过多层代理实现各个功能,各层只应该关注自己的异常,如果处理异常范围太广,会导致外层代理感知不到对应的异常,如:Bulkhead的回调处理的异常异常类型为Throwable,会导致外层所有的异常最内层处理掉,依赖于异常的Retry,CircuitBreaker就感知不到异常。如果多个功能组件设置了同名的回调方法,内层处理器可能会调用范围比较广的回调方法。
1. Maven导入依赖
<!--服务发现/注册:eureka client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--负载均衡:load balancer-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!-- 熔断:resilience4j -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
<!-- 隔仓 -->
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-bulkhead</artifactId>
</dependency>
<!-- 重试 -->
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-retry</artifactId>
</dependency>
<!-- 一定要导入AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 配置(公共配置)
#------------------------------------------# Servlet 容器配置#------------------------------------------#HTTP 服务端口,案例预留 30001 、 30002 、 30003 给服务消费者使用#server.port=30001# 关闭 bannerspring.main.banner-mode = off#------------------------------------------# 日志配置#------------------------------------------# 是否框架 debug 日志等级debug = false# 是否框架 trace 日志等级trace = false# 自己代码的日志等级logging.level.com.demo = trace#------------------------------------------# JSON 系列化和反序列化#------------------------------------------spring.jackson.date-format = yyyy-MM-dd#spring.jackson.date-format=yyyy-MM-dd hh:mm:ssspring.jackson.time-zone = GMT+8# 格式化输出spring.jackson.serialization.indent_output = true#------------------------------------------# 监控与管理: actuator#------------------------------------------# 默认情况下,除 shutdown 以外的所有端点均已启用。以下配置启用 shutdown 端点management.endpoint.shutdown.enabled = true# 通过 HPPT 公开所有端点。查看所有端点的 URL : http://localhost:30001/actuator/management.endpoints.web.exposure.include = *# 打印健康检查的详细信息未,未开启时的信息是 {"status":"UP"}management.endpoint.health.show-details = always# ------------------------------------------# Spring Cloud#------------------------------------------# 注册中 ⼼ 的地址 ,eureka-servereureka.client.service-url.defaultZone = http : //localhost : 10001/eureka
3. 组件
3.1 CircuitBreaker-断路器
1. 配置
###Resilience 4j## 打开 Resilience4j 报告熔断器和限速器监控指标的 Actuator 端点,默认是禁用的management.health.circuitbreakers.enabled = truemanagement.health.ratelimiters.enabled = true### 断路器的配置## 统计窗口,基于时间则创建对应长度的一个数组,如: 10 ,则通过一个长度为 10 的数组记录每一秒的请求数和失败数,然后循环写入记录的数据,基于数量统计时原理类似# 配置是基于时间段统计,还是基于请求数统计,默认 COUNT_BASEDresilience4j.circuitbreaker.configs.default.slidingWindowType = COUNT_BASED# 如果是基于请求数统计,则表示请求的数量,如果是基于时间段统计,表示统计的秒数,默认 100resilience4j.circuitbreaker.configs.default.slidingWindowSize = 3## 当慢调用比率超过阀值,则断路器打开# 慢调用比率阀值,默认 100%resilience4j.circuitbreaker.configs.default.slowCallRateThreshold = 100# 响应时间超过以下值即视为慢调用,默认 60000 毫秒resilience4j.circuitbreaker.configs.default.slowCallDurationThreshold = 20000## 状态维护# 故障率阀值,默认 50 ;也就是统计范围内的请求失败率超过这个阀值,断路器进入 Open 状态resilience4j.circuitbreaker.configs.default.failureRateThreshold = 50# 在计算故障率之前所需的最小调用次数,不达到这个值,不计算故障率。默认 100# 注意:如果统计窗口配置为 10 ,此处配置为 1 ,则第一次请求失败时故障率就会统计,即 100% ,会导致断路器打开resilience4j.circuitbreaker.configs.default.minimum-number-of-calls = 1#Open 状态持续时间,默认 60000 毫秒;也就是断路器断开这个毫秒数后,进入 HalfOpen 状态,可以尝试调用resilience4j.circuitbreaker.configs.default.waitDurationInOpenState = 10000000#HalfOpen 状态时允许的呼叫数,默认 10 ;也就是在 HalfOpen 状态下,可以发送这么多个请求,如果失败率还是# 高于故障率阀值,则返回到 Open 状态,否则切换到 Closed 状态resilience4j.circuitbreaker.configs.default.permittedNumberOfCallsInHalfOpenState= 10## 注册 Health 信息resilience4j.circuitbreaker.configs.default.registerHealthIndicator = true### 熔断器实例配置,也就是配置单个实例#backendA 为实例名称,其他属性也可以配置,此处只是个例子resilience4j.circuitbreaker.instances.backendA.registerHealthIndicator = true
2. 代码
@Service
public class SampleService implements ISampleService {
private static final Logger logger =
LoggerFactory.getLogger(SampleService.class);
@Autowired
private RestTemplate restTemplate;
@CircuitBreaker(name = "get", fallbackMethod = "reliable")
public Sample get(long id) {
}
/* 断路器的回调方法,断路器进行服务降级时调用。参数和返回值要和服务方法一致,需要加一个
CallNotPermittedException参数,这个只针对熔断进行降级。返回4*、5*响应码的异常由
Retry重试后降
级。这个异常如果需要被其它处理器感知到,则可以继续抛出 */
public Sample reliable(long id, CallNotPermittedException e) {
logger.info("服务降级..............Throwable..............");
logger.error("", e);
return new Sample(id, "服务降级,原因:" + e.getMessage());
}
}
注意:fallbackMethod可以不配置,fallback返回的值或者抛出的异常就是外层处理器得到的结果。
3.2 RateLimiter-限流器
限流RateLimiter是针对服务请求数量的一种自我保护机制,控制应用程序实例或某个服务对资源的消耗。当请求数量超出服务的处理能力时,超出的部分将被拒绝,排队或降级处理。
1. 配置
### 速率限制器的默认配置## 一个统计周期内可以发送的请求数,默认 50resilience4j.ratelimiter.configs.default.limitForPeriod = 1## 统计周期的时长,默认 500nsresilience4j.ratelimiter.configs.default.limitRefreshPeriod = 10s## 等待线程等多久后进行降级处理resilience4j.ratelimiter.configs.default.timeoutDuration = 0## 注册 Health 信息resilience4j.ratelimiter.configs.default.registerHealthIndicator = true
@Service
public class SampleService implements ISampleService {
private static final Logger logger =
LoggerFactory.getLogger(SampleService.class);
@Autowired
private RestTemplate restTemplate;
@CircuitBreaker(name = "get", fallbackMethod = "reliable")
@RateLimiter(name = "get", fallbackMethod = "reliable")
public Sample get(long id) {
}
/**
* 断路器的回调方法,服务降级时的调用的方法,参数和返回值要和服务方法一致,加一个Throwable
参数
*/
public Sample reliable(long id, CallNotPermittedException e) {
logger.info("服务降级............................");
return new Sample(id, "服务降级");
}
/**
* 限流器的回调方法,TPS超限时调用
*/
public Sample reliable(long id, RequestNotPermitted e) {
logger.info("服务降级............RequestNotPermitted................");
logger.error("", e);
return new Sample(id, "服务降级,原因:" + e.getMessage());
}
}
3.3 TimeLimiter-限时器
1. 配置
### 执行时间限制器的默认配置resilience4j.timelimiter.configs.default.timeout-duration = 1sresilience4j.timelimiter.configs.default.cancel-running-future = true
@Service
public class SampleServiceImpl2 implements SampleService {
/**
* 回调可以只在 @CircuitBreaker中配置
*/
@Override
@CircuitBreaker(name = "get", fallbackMethod = "reliable")
@RateLimiter(name = "get", fallbackMethod = "reliable")
@TimeLimiter(name = "get",fallbackMethod ="reliable" )
public CompletableFuture<Sample> get1(long id) {
return CompletableFuture.supplyAsync(() -> {
ResponseEntity<Sample> response = restTemplate.exchange(req,
Sample.class);
return respons
});
}
/**
* 断路器的回调方法
*/
public CompletableFuture<Sample> reliable(long id, CallNotPermittedException e) {
。。。
}
/**
* 限速器的回调方法
*/
public CompletableFuture<Sample> reliable(long id, RequestNotPermitted e) {
。。。
}
/**
* 限时器的回调方法
*/
public CompletableFuture<Sample> reliable(long id, TimeoutException e) {
logger.error(e.getClass().toString());
logger.info("服务降级,{}",e.getMessage());
return CompletableFuture.supplyAsync(
() -> new Sample(id, "服务降级,原因:" + e.getMessage()));
}
private String getBaseUrl() {
//使用服务ID
String baseUrl = "http://service-provider/api/v1/samples/";
return baseUrl;
}
}e.getBody();
注意:方法的返回值为CompletableFuture<Sample>,也就是需要返回一个异步任务,生成的限时器代理中通过任务调度线程池定时任务,检测异步任务在配置的时间内是否完成,如果未完成则抛出TimeoutException,如果任务限时内完成,则取消对应的定时检测任务。
3.4 Bulkhead-隔仓
通过线程池或者信号量控制对下游服务的调用并发量,如果并发数超过阀值,则直接返回,防止依赖的下游服务被并发请求冲击,同时防止由下游服务的响应时间过长而导致当前服务器线程全部阻塞。
基于信号量的实现(SemaphoreBulkhead):Semaphore
基于线程池的实现(FixedThreadPoolBulkhead):线程池ThreadPoolBulkhead,异步操作CompletableFuture,阻塞队列ArrayBlockingQueue
1. 导入依赖
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-bulkhead</artifactId>
</dependency>
### 隔舱的默认配置 , 默认使用信号量# 允许的并发请求数量,默认 25resilience4j.bulkhead.configs.default.maxConcurrentCalls = 2# 请求数量超限后,其它线程阻塞的时间,默认 0resilience4j.bulkhead.configs.default.maxWaitDuration = 10ms
3. 代码
@Service
public class SampleService implements ISampleService {
private static final Logger logger =
LoggerFactory.getLogger(SampleService.class);
@Autowired
private RestTemplate restTemplate;
@CircuitBreaker(name = "get", fallbackMethod = "reliable")
@RateLimiter(name = "get", fallbackMethod = "reliable")
@TimeLimiter(name = "get",fallbackMethod ="reliable" )
@Bulkhead(name = "get", fallbackMethod = "reliable")
public CompletableFuture<Sample> get(long id) {
}
/**
* 断路器的回调方法
*/
public CompletableFuture<Sample>reliable(long id, CallNotPermittedException e) {
。。。
}
/**
* 限速器的回调方法
*/
public CompletableFuture<Sample>reliable(long id, RequestNotPermitted e) {
。。。
}
/**
* 限时器的回调方法
*/
public CompletableFuture<Sample> reliable(long id, TimeoutException e) {
logger.error(e.getClass().toString());
logger.info("服务降级,{}",e.getMessage());
return CompletableFuture.supplyAsync(
() -> new Sample(id, "服务降级,原因:" + e.getMessage()));
}
/**
* 隔舱的回调方法,并发超量时调用
*/
public CompletableFuture<Sample> reliable(long id, BulkheadFullException e)
{
logger.info("服务降级............BulkheadFullException................");
return CompletableFuture.supplyAsync(
() -> new Sample(id, "服务降级,原因:" + e.getMessage()));
}
}
3.5 Retry-重试
解决网络不稳定,隔仓满等临时性的故障。
1. 导入依赖
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-retry</artifactId>
</dependency>
2. 配置
### 重试的默认配置## 重试次数,默认 3 。这个数量是包含了第一次调用的resilience4j.retry.configs.default.max-attempts = 3## 重试的时间间隔,默认 500msresilience4j.retry.configs.default.waitDuration = 1s## 下次重试时延迟间隔时间resilience4j.retry.configs.default.enableExponentialBackoff = true## 下次重试时延迟间隔时间的倍数,如:第 1 此失败了,那么下次间隔waitDuration*exponentialBackoffMultiplier 的时间后重试resilience4j.retry.configs.default.exponentialBackoffMultiplier = 2## 下次重试时延迟间隔时间的倍数,如:第 1 此失败了,那么下次间隔waitDuration*exponentialBackoffMultiplier 的时间后重试resilience4j.retry.configs.default.exponentialBackoffMultiplier = 2## 哪些异常是要重试的。默认都要重试resilience4j.retry.configs.default.retryExceptions = org.springframework.web.client.HttpServerErrorException,java.util.concurrent.TimeoutException,java.io.IOException## 哪些异常是要忽略的,异常类型必须在 classpath 中resilience4j.retry.configs.default.ignoreExceptions = com.demo.cloud.customer.service.ServiceException
3. 代码
@Service
public class SampleService implements ISampleService {
private static final Logger logger =
LoggerFactory.getLogger(SampleService.class);
@Autowired
private RestTemplate restTemplate;
//如果给@Retry设置了捕获类型为Throwable的回调方法,则不要给其他模块设置同名的回调方法,
//否则不管什么异常都会被前置的模块捕获了。如: @CircuitBreaker也设置了回调方法,
//( fallbackMethod = "reliable"),则调用出现异常时
//(如:500响应,即exchange抛出HttpServerErrorException),
//断路器会捕获异常,然后进行回调匹配,会匹配到reliable(long id, Throwable e)方法,这个
方法没有
//再次抛出异常,则@Retry感知不到异常
@CircuitBreaker(name = "get", fallbackMethod = "reliable")
@RateLimiter(name = "get", fallbackMethod = "reliable")
@TimeLimiter(name = "get",fallbackMethod ="reliable" )
@Bulkhead(name = "get", fallbackMethod = "reliable")
@Retry(name = "get",fallbackMethod ="reliable1")
public CompletableFuture<Sample> get(long id) {
}
/**
* 断路器的回调方法
*/
public CompletableFuture<Sample> reliable(long id, CallNotPermittedException e) {
。。。
}
/**
* 限速器的回调方法
*/
public CompletableFuture<Sample> reliable(long id, RequestNotPermitted e) {
。。。
}
/**
* 限时器的回调方法
*/
public CompletableFuture<Sample> reliable(long id, TimeoutException e) {
logger.error(e.getClass().toString());
logger.info("服务降级,{}",e.getMessage());
return CompletableFuture.supplyAsync(
() -> new Sample(id, "服务降级,原因:" + e.getMessage()));
}
/**
* 隔舱的回调方法,并发超量时调用
*/
public CompletableFuture<Sample> reliable(long id, BulkheadFullException e)
{
logger.info("服务降级............BulkheadFullException................");
return CompletableFuture.supplyAsync(
() -> new Sample(id, "服务降级,原因:" + e.getMessage()));
}
/**
* 重试失败的回调方法
*
* @param id
* @param e
* @return
*/
private CompletableFuture<Sample> reliable1(long id, Throwable e) {
logger.error(e.getClass().toString());
logger.info("服务降级,{}",e.getMessage());
return CompletableFuture.supplyAsync(
() -> new Sample(id, "服务降级,原因:" + e.getMessage()));
}
}
如果不适用限时器则返回值类型不需要包装为异步任务CompletableFuture<Sample>
注意:重试捕获到的异常后,不会马上调用降级方法,而是先进行重试,如果最后一次重试都捕获到异常,则最后一次的异常进行降级处理。