Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

spring-boot-resilience4j弹簧靴弹性 4j

Agent Skill

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

总安装

17,016

周安装

709

GitHub Stars

229

下载量

5,672
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:spring-boot-resilience4j(弹簧靴弹性 4j)
来源仓库:https://github.com/giuseppe-trisciuoglio/developer-kit
仓库路径:skills/spring-boot-resilience4j
安装命令:
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-resilience4j
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-resilience4j

简介

使用 Resilience4j 的 Spring Boot 微服务的容错和弹性模式。

  • 提供六种核心模式:断路器、指数退避重试、速率限制器、舱壁(信号量和线程池)、时间限制器和回退机制
  • 与 Spring Boot 3.x AOP 基于注解的集成;模式可以堆叠在单个方法上以实现全面的容错
  • 包括 YAML 中所有模式的配置示例,以及用于监控断路器状态和指标的运行状况指示器和执行器端点集成
  • 最佳实践包括幂等重试、适当的失败阈值、构造函数注入以及通过回退方法进行优雅降级

SKILL.md

Spring Boot Resilience4j Patterns

Overview

Provides Resilience4j patterns (circuit breaker, retry, rate limiter, bulkhead, time limiter, fallback) for Spring Boot 3.x fault tolerance with configuration and testing workflows.

When to Use

  • Implementing fault tolerance and preventing cascading failures
  • Adding circuit breakers, retry logic, or rate limiting to service calls
  • Handling transient failures with exponential backoff
  • Protecting services from overload and resource exhaustion
  • Combining multiple patterns for comprehensive resilience

Instructions

1. Setup and Dependencies

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).

2. Circuit Breaker Pattern

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.

3. Retry Pattern

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.

4. Rate Limiter Pattern

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

5. Bulkhead Pattern

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

6. Time Limiter Pattern

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

7. Combining Multiple Patterns

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.

8. Exception Handling and Monitoring

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 patterns
  • GET /actuator/circuitbreakers - Circuit breaker states
  • GET /actuator/metrics - Custom resilience metrics

Testing & Verification Workflow

  1. Circuit Breaker: Call endpoint with failures → check GET /actuator/circuitbreakers shows OPEN → wait waitDurationInOpenState → verify state transitions to HALF_OPENCLOSED
  2. Retry: Enable resilience4j.retry.metrics.enabled: true → invoke endpoint → verify retry.{instance}.successful-calls-with-retry-attempts metric increases
  3. Rate Limiter: Send requests exceeding limitForPeriod → verify 429 status → check GET /actuator/ratelimiters shows LIMITED
  4. Bulkhead: Load test with concurrent requests exceeding maxConcurrentCalls → verify excess requests fail immediately with BulkheadFullException
  5. Time Limiter: Mock async delay beyond timeoutDuration → verify fallback triggers after timeout

See @references/testing-patterns.md for unit and integration testing strategies.

Best Practices

  • Provide fallback methods: Ensure graceful degradation with meaningful responses
  • Use exponential backoff: Prevent overwhelming recovering services (exponentialBackoffMultiplier: 2)
  • Set appropriate thresholds: failureRateThreshold between 50-70%
  • Use constructor injection: Never use field injection for Resilience4j dependencies
  • Enable health indicators: Set registerHealthIndicator: true for all patterns
  • Retry only transient errors: Network timeouts, 5xx; skip 4xx and business exceptions
  • Size bulkheads based on load: Calculate thread pool and semaphore sizes from expected concurrency
  • Document fallback behavior: Make fallback logic clear and predictable

Constraints and Warnings

  • Fallback methods must have the same signature plus an optional exception parameter
  • Circuit breaker state is per-instance; ensure proper bean scoping in multi-tenant scenarios
  • Retry operations must be idempotent (may execute multiple times)
  • Do not use circuit breakers for operations that must always complete; use timeouts instead
  • Rate limiters can cause thread blocking; configure appropriate wait durations
  • Be cautious with @Retry on non-idempotent operations like POST requests
  • Monitor memory when using thread pool bulkheads with high concurrency

Examples

Before → After: Circuit Breaker

// BEFORE: No protection
public PaymentResponse processPayment(PaymentRequest request) {
    return restTemplate.postForObject("http://payment-api/process", request, PaymentResponse.class);
}

// AFTER: Circuit breaker with fallback
@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();
}

Before → After: Retry with Backoff

// BEFORE: Single attempt
public Order getOrder(Long orderId) {
    return orderRepository.findById(orderId).orElseThrow(() -> new OrderNotFoundException(orderId));
}

// AFTER: Retry with exponential backoff
@Retry(name = "orderService", maxAttempts = 3, waitDuration = @WaitDuration(500L), 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); }

Before → After: Rate Limiting

// BEFORE: Unbounded requests
@GetMapping("/api/data") public Data fetchData() { return dataService.process(); }

// AFTER: Rate limited
@RateLimiter(name = "dataService", fallbackMethod = "rateLimitFallback")
@GetMapping("/api/data") public Data fetchData() { return dataService.process(); }
private ResponseEntity<ErrorResponse> rateLimitFallback(Exception ex) {
    return ResponseEntity.status(429).body(new ErrorResponse("TOO_MANY_REQUESTS", "Rate limit exceeded"));
}

See also: Configuration Reference · Testing Patterns · Examples · Resilience4j Docs · Actuator Skill

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.7%
按下载量换算2,025

Claude

30.86%
按下载量换算1,750

Cursor

20.3%
按下载量换算1,151

Gemini CLI

9.75%
按下载量换算553

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills