spring-boot-resilience4j by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-resilience4jResilience4j 是一个轻量级的容错库,专为 Java 8+ 和函数式编程设计。它提供了处理分布式系统故障的模式,包括断路器、速率限制器、重试机制、舱壁和时限器。本技能演示了如何将 Resilience4j 与 Spring Boot 3.x 集成,以构建能够优雅处理外部服务故障并防止系统级联故障的弹性微服务。
在 Spring Boot 应用程序中实现弹性模式时,请使用此技能:
Resilience4j 是一个轻量级、可组合的库,用于添加容错能力,无需外部基础设施。它提供了基于注解的模式,可与 Spring Boot 的 AOP 和 Actuator 无缝集成。
将 Resilience4j 依赖项添加到您的项目中。对于 Maven,请添加到 pom.xml:
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
<version>2.2.0</version> // 使用最新的稳定版本
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
对于 Gradle,请添加到 build.gradle:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
implementation "io.github.resilience4j:resilience4j-spring-boot3:2.2.0"
implementation "org.springframework.boot:spring-boot-starter-aop"
implementation "org.springframework.boot:spring-boot-starter-actuator"
使用 @EnableAspectJAutoProxy 启用 AOP 注解处理(由 Spring Boot 自动配置)。
将 @CircuitBreaker 注解应用于调用外部服务的方法:
@Service
public class PaymentService {
private final RestTemplate restTemplate;
public PaymentService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public PaymentResponse processPayment(PaymentRequest request) {
return restTemplate.postForObject("http://payment-api/process",
request, PaymentResponse.class);
}
private PaymentResponse paymentFallback(PaymentRequest request, Exception ex) {
return PaymentResponse.builder()
.status("PENDING")
.message("Service temporarily unavailable")
.build();
}
}
在 application.yml 中配置:
resilience4j:
circuitbreaker:
configs:
default:
registerHealthIndicator: true
slidingWindowSize: 10
minimumNumberOfCalls: 5
failureRateThreshold: 50
waitDurationInOpenState: 10s
instances:
paymentService:
baseConfig: default
有关完整的断路器配置选项,请参阅 @references/configuration-reference.md。
应用 @Retry 注解以实现暂时性故障恢复:
@Service
public class ProductService {
private final RestTemplate restTemplate;
public ProductService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Retry(name = "productService", fallbackMethod = "getProductFallback")
public Product getProduct(Long productId) {
return restTemplate.getForObject(
"http://product-api/products/" + productId,
Product.class);
}
private Product getProductFallback(Long productId, Exception ex) {
return Product.builder()
.id(productId)
.name("Unavailable")
.available(false)
.build();
}
}
在 application.yml 中配置重试:
resilience4j:
retry:
configs:
default:
maxAttempts: 3
waitDuration: 500ms
enableExponentialBackoff: true
exponentialBackoffMultiplier: 2
instances:
productService:
baseConfig: default
maxAttempts: 5
有关重试异常配置,请参阅 @references/configuration-reference.md。
应用 @RateLimiter 来控制请求速率:
@Service
public class NotificationService {
private final EmailClient emailClient;
public NotificationService(EmailClient emailClient) {
this.emailClient = emailClient;
}
@RateLimiter(name = "notificationService",
fallbackMethod = "rateLimitFallback")
public void sendEmail(EmailRequest request) {
emailClient.send(request);
}
private void rateLimitFallback(EmailRequest request, Exception ex) {
throw new RateLimitExceededException(
"Too many requests. Please try again later.");
}
}
在 application.yml 中配置:
resilience4j:
ratelimiter:
configs:
default:
registerHealthIndicator: true
limitForPeriod: 10
limitRefreshPeriod: 1s
timeoutDuration: 500ms
instances:
notificationService:
baseConfig: default
limitForPeriod: 5
应用 @Bulkhead 来隔离资源。对于同步方法,使用 type = SEMAPHORE:
@Service
public class ReportService {
private final ReportGenerator reportGenerator;
public ReportService(ReportGenerator reportGenerator) {
this.reportGenerator = reportGenerator;
}
@Bulkhead(name = "reportService", type = Bulkhead.Type.SEMAPHORE)
public Report generateReport(ReportRequest request) {
return reportGenerator.generate(request);
}
}
对于异步/CompletableFuture 方法,使用 type = THREADPOOL:
@Service
public class AnalyticsService {
@Bulkhead(name = "analyticsService", type = Bulkhead.Type.THREADPOOL)
public CompletableFuture<AnalyticsResult> runAnalytics(
AnalyticsRequest request) {
return CompletableFuture.supplyAsync(() ->
analyticsEngine.analyze(request));
}
}
在 application.yml 中配置:
resilience4j:
bulkhead:
configs:
default:
maxConcurrentCalls: 10
maxWaitDuration: 100ms
instances:
reportService:
baseConfig: default
maxConcurrentCalls: 5
thread-pool-bulkhead:
instances:
analyticsService:
maxThreadPoolSize: 8
将 @TimeLimiter 应用于异步方法以强制执行超时边界:
@Service
public class SearchService {
@TimeLimiter(name = "searchService", fallbackMethod = "searchFallback")
public CompletableFuture<SearchResults> search(SearchQuery query) {
return CompletableFuture.supplyAsync(() ->
searchEngine.executeSearch(query));
}
private CompletableFuture<SearchResults> searchFallback(
SearchQuery query, Exception ex) {
return CompletableFuture.completedFuture(
SearchResults.empty("Search timed out"));
}
}
在 application.yml 中配置:
resilience4j:
timelimiter:
configs:
default:
timeoutDuration: 2s
cancelRunningFuture: true
instances:
searchService:
baseConfig: default
timeoutDuration: 3s
在单个方法上堆叠多种模式以实现全面的容错能力:
@Service
public class OrderService {
@CircuitBreaker(name = "orderService")
@Retry(name = "orderService")
@RateLimiter(name = "orderService")
@Bulkhead(name = "orderService")
public Order createOrder(OrderRequest request) {
return orderClient.createOrder(request);
}
}
执行顺序:重试 → 断路器 → 速率限制器 → 舱壁 → 方法
所有模式都应引用相同的命名配置实例以确保一致性。
使用 @RestControllerAdvice 创建全局异常处理器:
@RestControllerAdvice
public class ResilienceExceptionHandler {
@ExceptionHandler(CallNotPermittedException.class)
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public ErrorResponse handleCircuitOpen(CallNotPermittedException ex) {
return new ErrorResponse("SERVICE_UNAVAILABLE",
"Service currently unavailable");
}
@ExceptionHandler(RequestNotPermitted.class)
@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
public ErrorResponse handleRateLimited(RequestNotPermitted ex) {
return new ErrorResponse("TOO_MANY_REQUESTS",
"Rate limit exceeded");
}
@ExceptionHandler(BulkheadFullException.class)
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public ErrorResponse handleBulkheadFull(BulkheadFullException ex) {
return new ErrorResponse("CAPACITY_EXCEEDED",
"Service at capacity");
}
}
在 application.yml 中启用 Actuator 端点以监控弹性模式:
management:
endpoints:
web:
exposure:
include: health,metrics,circuitbreakers,retries,ratelimiters
endpoint:
health:
show-details: always
health:
circuitbreakers:
enabled: true
ratelimiters:
enabled: true
访问监控端点:
GET /actuator/health - 整体健康状况,包括弹性模式GET /actuator/circuitbreakers - 断路器状态GET /actuator/metrics - 自定义弹性指标exponentialBackoffMultiplier: 2)failureRateThreshold 设置在 50-70% 之间registerHealthIndicator: true,以便与 Spring Boot 健康检查集成@Retry 时要谨慎。@Service
public class PaymentService {
public PaymentResponse processPayment(PaymentRequest request) {
return restTemplate.postForObject("http://payment-api/process",
request, PaymentResponse.class);
}
}
@Service
public class PaymentService {
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public PaymentResponse processPayment(PaymentRequest request) {
return restTemplate.postForObject("http://payment-api/process",
request, PaymentResponse.class);
}
private PaymentResponse paymentFallback(PaymentRequest request, Exception ex) {
return PaymentResponse.builder()
.status("PENDING")
.message("Service temporarily unavailable")
.build();
}
}
public Order getOrder(Long orderId) {
return orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException(orderId));
}
@Retry(name = "orderService", fallbackMethod = "getOrderFallback")
public Order getOrder(Long orderId) {
return orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException(orderId));
}
private Order getOrderFallback(Long orderId, Exception ex) {
return Order.cachedOrder(orderId);
}
@RestController
public class ApiController {
@GetMapping("/api/data")
public Data fetchData() {
return dataService.processLargeDataset();
}
}
@RestController
public class ApiController {
@RateLimiter(name = "dataService", fallbackMethod = "rateLimitFallback")
@GetMapping("/api/data")
public Data fetchData() {
return dataService.processLargeDataset();
}
private ResponseEntity<ErrorResponse> rateLimitFallback(Exception ex) {
return ResponseEntity.status(429)
.body(new ErrorResponse("TOO_MANY_REQUESTS", "Rate limit exceeded"));
}
}
@Service
public class ReportService {
public Report generateReport(ReportRequest request) {
return reportGenerator.generate(request);
}
}
@Service
public class ReportService {
@Bulkhead(name = "reportService", type = Bulkhead.Type.SEMAPHORE)
public Report generateReport(ReportRequest request) {
return reportGenerator.generate(request);
}
}
每周安装数
361
代码仓库
GitHub 星标数
173
首次出现
2026年2月3日
安全审计
安装于
claude-code281
gemini-cli276
opencode275
cursor272
codex271
github-copilot256
Resilience4j is a lightweight fault tolerance library designed for Java 8+ and functional programming. It provides patterns for handling failures in distributed systems including circuit breakers, rate limiters, retry mechanisms, bulkheads, and time limiters. This skill demonstrates how to integrate Resilience4j with Spring Boot 3.x to build resilient microservices that can gracefully handle external service failures and prevent cascading failures across the system.
To implement resilience patterns in Spring Boot applications, use this skill when:
Resilience4j is a lightweight, composable library for adding fault tolerance without requiring external infrastructure. It provides annotation-based patterns that integrate seamlessly with Spring Boot's AOP and Actuator.
Add Resilience4j dependencies to your project. For Maven, add to pom.xml:
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
<version>2.2.0</version> // Use latest stable version
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
For Gradle, add to build.gradle:
implementation "io.github.resilience4j:resilience4j-spring-boot3:2.2.0"
implementation "org.springframework.boot:spring-boot-starter-aop"
implementation "org.springframework.boot:spring-boot-starter-actuator"
Enable AOP annotation processing with @EnableAspectJAutoProxy (auto-configured by Spring Boot).
Apply @CircuitBreaker annotation to methods calling external services:
@Service
public class PaymentService {
private final RestTemplate restTemplate;
public PaymentService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public PaymentResponse processPayment(PaymentRequest request) {
return restTemplate.postForObject("http://payment-api/process",
request, PaymentResponse.class);
}
private PaymentResponse paymentFallback(PaymentRequest request, Exception ex) {
return PaymentResponse.builder()
.status("PENDING")
.message("Service temporarily unavailable")
.build();
}
}
Configure in application.yml:
resilience4j:
circuitbreaker:
configs:
default:
registerHealthIndicator: true
slidingWindowSize: 10
minimumNumberOfCalls: 5
failureRateThreshold: 50
waitDurationInOpenState: 10s
instances:
paymentService:
baseConfig: default
See @references/configuration-reference.md for complete circuit breaker configuration options.
Apply @Retry annotation for transient failure recovery:
@Service
public class ProductService {
private final RestTemplate restTemplate;
public ProductService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Retry(name = "productService", fallbackMethod = "getProductFallback")
public Product getProduct(Long productId) {
return restTemplate.getForObject(
"http://product-api/products/" + productId,
Product.class);
}
private Product getProductFallback(Long productId, Exception ex) {
return Product.builder()
.id(productId)
.name("Unavailable")
.available(false)
.build();
}
}
Configure retry in application.yml:
resilience4j:
retry:
configs:
default:
maxAttempts: 3
waitDuration: 500ms
enableExponentialBackoff: true
exponentialBackoffMultiplier: 2
instances:
productService:
baseConfig: default
maxAttempts: 5
See @references/configuration-reference.md for retry exception configuration.
Apply @RateLimiter to control request rates:
@Service
public class NotificationService {
private final EmailClient emailClient;
public NotificationService(EmailClient emailClient) {
this.emailClient = emailClient;
}
@RateLimiter(name = "notificationService",
fallbackMethod = "rateLimitFallback")
public void sendEmail(EmailRequest request) {
emailClient.send(request);
}
private void rateLimitFallback(EmailRequest request, Exception ex) {
throw new RateLimitExceededException(
"Too many requests. Please try again later.");
}
}
Configure in application.yml:
resilience4j:
ratelimiter:
configs:
default:
registerHealthIndicator: true
limitForPeriod: 10
limitRefreshPeriod: 1s
timeoutDuration: 500ms
instances:
notificationService:
baseConfig: default
limitForPeriod: 5
Apply @Bulkhead to isolate resources. Use type = SEMAPHORE for synchronous methods:
@Service
public class ReportService {
private final ReportGenerator reportGenerator;
public ReportService(ReportGenerator reportGenerator) {
this.reportGenerator = reportGenerator;
}
@Bulkhead(name = "reportService", type = Bulkhead.Type.SEMAPHORE)
public Report generateReport(ReportRequest request) {
return reportGenerator.generate(request);
}
}
Use type = THREADPOOL for async/CompletableFuture methods:
@Service
public class AnalyticsService {
@Bulkhead(name = "analyticsService", type = Bulkhead.Type.THREADPOOL)
public CompletableFuture<AnalyticsResult> runAnalytics(
AnalyticsRequest request) {
return CompletableFuture.supplyAsync(() ->
analyticsEngine.analyze(request));
}
}
Configure in application.yml:
resilience4j:
bulkhead:
configs:
default:
maxConcurrentCalls: 10
maxWaitDuration: 100ms
instances:
reportService:
baseConfig: default
maxConcurrentCalls: 5
thread-pool-bulkhead:
instances:
analyticsService:
maxThreadPoolSize: 8
Apply @TimeLimiter to async methods to enforce timeout boundaries:
@Service
public class SearchService {
@TimeLimiter(name = "searchService", fallbackMethod = "searchFallback")
public CompletableFuture<SearchResults> search(SearchQuery query) {
return CompletableFuture.supplyAsync(() ->
searchEngine.executeSearch(query));
}
private CompletableFuture<SearchResults> searchFallback(
SearchQuery query, Exception ex) {
return CompletableFuture.completedFuture(
SearchResults.empty("Search timed out"));
}
}
Configure in application.yml:
resilience4j:
timelimiter:
configs:
default:
timeoutDuration: 2s
cancelRunningFuture: true
instances:
searchService:
baseConfig: default
timeoutDuration: 3s
Stack multiple patterns on a single method for comprehensive fault tolerance:
@Service
public class OrderService {
@CircuitBreaker(name = "orderService")
@Retry(name = "orderService")
@RateLimiter(name = "orderService")
@Bulkhead(name = "orderService")
public Order createOrder(OrderRequest request) {
return orderClient.createOrder(request);
}
}
Execution order: Retry → CircuitBreaker → RateLimiter → Bulkhead → Method
All patterns should reference the same named configuration instance for consistency.
Create a global exception handler using @RestControllerAdvice:
@RestControllerAdvice
public class ResilienceExceptionHandler {
@ExceptionHandler(CallNotPermittedException.class)
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public ErrorResponse handleCircuitOpen(CallNotPermittedException ex) {
return new ErrorResponse("SERVICE_UNAVAILABLE",
"Service currently unavailable");
}
@ExceptionHandler(RequestNotPermitted.class)
@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
public ErrorResponse handleRateLimited(RequestNotPermitted ex) {
return new ErrorResponse("TOO_MANY_REQUESTS",
"Rate limit exceeded");
}
@ExceptionHandler(BulkheadFullException.class)
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public ErrorResponse handleBulkheadFull(BulkheadFullException ex) {
return new ErrorResponse("CAPACITY_EXCEEDED",
"Service at capacity");
}
}
Enable Actuator endpoints for monitoring resilience patterns in application.yml:
management:
endpoints:
web:
exposure:
include: health,metrics,circuitbreakers,retries,ratelimiters
endpoint:
health:
show-details: always
health:
circuitbreakers:
enabled: true
ratelimiters:
enabled: true
Access monitoring endpoints:
GET /actuator/health - Overall health including resilience patternsGET /actuator/circuitbreakers - Circuit breaker statesGET /actuator/metrics - Custom resilience metricsexponentialBackoffMultiplier: 2)failureRateThreshold between 50-70% depending on acceptable error ratesregisterHealthIndicator: true for all patterns to integrate with Spring Boot health@Retry on non-idempotent operations like POST requests.@Service
public class PaymentService {
public PaymentResponse processPayment(PaymentRequest request) {
return restTemplate.postForObject("http://payment-api/process",
request, PaymentResponse.class);
}
}
@Service
public class PaymentService {
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public PaymentResponse processPayment(PaymentRequest request) {
return restTemplate.postForObject("http://payment-api/process",
request, PaymentResponse.class);
}
private PaymentResponse paymentFallback(PaymentRequest request, Exception ex) {
return PaymentResponse.builder()
.status("PENDING")
.message("Service temporarily unavailable")
.build();
}
}
public Order getOrder(Long orderId) {
return orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException(orderId));
}
@Retry(name = "orderService", fallbackMethod = "getOrderFallback")
public Order getOrder(Long orderId) {
return orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException(orderId));
}
private Order getOrderFallback(Long orderId, Exception ex) {
return Order.cachedOrder(orderId);
}
@RestController
public class ApiController {
@GetMapping("/api/data")
public Data fetchData() {
return dataService.processLargeDataset();
}
}
@RestController
public class ApiController {
@RateLimiter(name = "dataService", fallbackMethod = "rateLimitFallback")
@GetMapping("/api/data")
public Data fetchData() {
return dataService.processLargeDataset();
}
private ResponseEntity<ErrorResponse> rateLimitFallback(Exception ex) {
return ResponseEntity.status(429)
.body(new ErrorResponse("TOO_MANY_REQUESTS", "Rate limit exceeded"));
}
}
@Service
public class ReportService {
public Report generateReport(ReportRequest request) {
return reportGenerator.generate(request);
}
}
@Service
public class ReportService {
@Bulkhead(name = "reportService", type = Bulkhead.Type.SEMAPHORE)
public Report generateReport(ReportRequest request) {
return reportGenerator.generate(request);
}
}
Weekly Installs
361
Repository
GitHub Stars
173
First Seen
Feb 3, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code281
gemini-cli276
opencode275
cursor272
codex271
github-copilot256
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装