Spring Boot整合Resilience4j教程
精心整理了最新的面试资料和简历模板,有需要的可以自行获取
点击前往百度网盘获取
点击前往夸克网盘获取
以下是将Spring Boot与Resilience4j整合的详细教程,包含基础配置和核心功能示例:
Spring Boot整合Resilience4j教程
Resilience4j提供容错机制(断路器、重试、限流等),帮助构建弹性微服务。
一、环境准备
-
创建项目
使用Spring Initializr生成项目,选择:- Spring Boot 3.x
- 依赖:Spring Web, Spring Actuator, Lombok
-
添加Resilience4j依赖
在pom.xml
中:<!-- Resilience4j 核心 --> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring-boot3</artifactId> <version>2.1.0</version> </dependency> <!-- AOP支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
二、配置Resilience4j
在application.yml
中添加配置:
resilience4j:
circuitbreaker:
instances:
myService:
register-health-indicator: true
failure-rate-threshold: 50 # 触发断路器的失败率阈值(%)
minimum-number-of-calls: 5 # 最小调用次数
sliding-window-type: COUNT_BASED
sliding-window-size: 10 # 统计窗口大小
wait-duration-in-open-state: 5s # 断路器开启后的等待时间
permitted-number-of-calls-in-half-open-state: 3
retry:
instances:
myRetry:
max-attempts: 3 # 最大重试次数
wait-duration: 500ms # 重试间隔
三、实现断路器(Circuit Breaker)
-
定义Service类
@Service public class ExternalService { // 模拟外部服务调用 public String callExternalService() { if (Math.random() > 0.5) { throw new RuntimeException("External service error"); } return "Success"; } }
-
添加断路器逻辑
@Service public class MyService { private final ExternalService externalService; public MyService(ExternalService externalService) { this.externalService = externalService; } @CircuitBreaker(name = "myService", fallbackMethod = "fallback") public String callWithCircuitBreaker() { return externalService.callExternalService(); } // Fallback方法需与原方法参数一致,并添加异常参数 private String fallback(Exception e) { return "Fallback response: Service unavailable"; } }
四、添加重试机制(Retry)
@RestController
@RequestMapping("/api")
public class ApiController {
private final MyService myService;
public ApiController(MyService myService) {
this.myService = myService;
}
@GetMapping("/data")
@Retry(name = "myRetry", fallbackMethod = "retryFallback")
public String getData() {
return myService.callWithCircuitBreaker();
}
public String retryFallback(Exception e) {
return "Retry exhausted. Fallback response";
}
}
五、监控与端点
-
启用Actuator端点
在application.yml
:management: endpoints: web: exposure: include: health,circuitbreakers,retries
-
访问监控信息
- 断路器状态:
http://localhost:8080/actuator/health
- 所有断路器:
http://localhost:8080/actuator/circuitbreakers
- 重试信息:
http://localhost:8080/actuator/retries
- 断路器状态:
六、测试断路器行为
-
快速失败触发
连续发送多个请求,让超过50%的请求失败:curl http://localhost:8080/api/data
-
观察断路器状态
当失败率达到阈值后,后续请求直接进入fallback,持续5秒后进入半开状态。
七、高级配置(可选)
-
组合使用Bulkhead(舱壁隔离)
限制并发调用数量:reselience4j: bulkhead: instances: myBulkhead: max-concurrent-calls: 20
使用注解:
@Bulkhead(name = "myBulkhead")
-
Rate Limiter(限流)
控制时间窗口内的请求次数:reselience4j: ratelimiter: instances: myLimiter: limit-for-period: 10 limit-refresh-period: 1s
使用注解:
@RateLimiter(name = "myLimiter")
八、常见问题
-
注解不生效
确保添加了@EnableAspectJAutoProxy
或在启动类添加:@SpringBootApplication @EnableCircuitBreaker // 对于旧版本可能需要 public class Application { ... }
-
版本兼容性
Spring Boot 3.x需使用Resilience4j 2.x+,检查依赖版本匹配。
完成以上步骤后,您的Spring Boot应用已具备弹性容错能力。建议通过单元测试和压力测试验证不同故障场景下的系统行为。