SpringBoot3整合Resilience4j

SpringBoot3整合Resilience4j

起男 21 2025-06-06

SpringBoot3整合Resilience4j

依赖

	implementation("io.github.resilience4j:resilience4j-spring-boot3:2.2.0")
	implementation("org.springframework.boot:spring-boot-starter-aop")

配置文件

resilience4j:
  timelimiter: #超时
    instances: #实例名
      timeoutService:
        timeoutDuration: 2s # 超时时间为2秒
  circuitbreaker: #熔断
    instances:
      circuitbreakerService:
        slidingWindowSize: 10 # 滑动窗口大小为10
        failureRateThreshold: 50 # 失败率阈值为50%
        waitDurationInOpenState: 10s # 打开状态等待时间为10秒
  ratelimiter: #限流 限制请求速率
    instances:
      ratelimiterService:
        limitForPeriod: 1 # 每个周期允许的最大请求数为1
        limitRefreshPeriod: 10s # 速率限制刷新周期为10秒
        timeoutDuration: 500ms # 等待许可的超时时间为500毫秒
  retry: #重试
    instances:
      retryService:
        maxAttempts: 5 # 最大重试次数为5次
        waitDuration: 1000ms # 重试间隔为1000毫秒(1秒)
        enableExponentialBackoff: true # 启用指数回退
        exponentialBackoffMultiplier: 1.5 # 指数回退倍数为1.5
        retryExceptions:
          - java.lang.RuntimeException # 需要重试的异常类型
  bulkhead: #批隔离 限制并发数量
    instances:
      bulkheadService:
        maxConcurrentCalls: 3 # 批隔离允许的最大并发调用数为5
        maxWaitDuration: 1s # 等待许可的最大时间为1秒

使用

@RestController
public class MyController {

    //重试
    @Retry(name = "retryService",fallbackMethod = "fallBack")
    @GetMapping("test01/{msg}")
    public String test01(@PathVariable String msg){
        System.out.println("ok");
        if("1".equals(msg)){
            throw new RuntimeException("服务调用失败");
        }
        return "ok";
    }
    //熔断
    @CircuitBreaker(name = "circuitbreakerService",fallbackMethod = "fallBack")
    @GetMapping("test02/{msg}")
    public String test02(@PathVariable String msg){
        System.out.println("ok");
        if("1".equals(msg)){
            throw new RuntimeException("服务调用失败");
        }
        return "ok";
    }
    //限流
    @RateLimiter(name = "ratelimiterService",fallbackMethod = "fallBack")
    @GetMapping("test03")
    public String test03(){
        System.out.println("ok");
        return "ok";
    }
    //超时,对返回类型有要求
    @TimeLimiter(name = "timeoutService",fallbackMethod = "fallBack2")
    @GetMapping("test04/{i}")
    public CompletableFuture<String> test04(@PathVariable int i){
        return CompletableFuture.supplyAsync(()->{
            System.out.println("ok");
            try {
                Thread.sleep(1000*i);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return "ok";
        });
    }
    //批隔离
    @Bulkhead(name = "bulkheadService",fallbackMethod = "fallBack")
    @SneakyThrows
    @GetMapping("test05")
    public String test05(){
        System.out.println("ok");
        Thread.sleep(5000);
        return "ok";
    }

    public String fallBack(Throwable throwable){
        System.out.println("fallBck:"+throwable.getMessage());
        return "error";
    }
    //超时使用
    public CompletableFuture<String> fallBack2(int i,Throwable throwable){
        return CompletableFuture.supplyAsync(()->{
            System.out.println("i:"+i);
            System.out.println("fallBck:"+throwable.getMessage());
            return "error";
        });
    }
}

监听器

@Component
@Slf4j
@AllArgsConstructor
public class ResilienceListener {

    private final RetryRegistry retryRegistry;
    private final TimeLimiterRegistry timeLimiterRegistry;
    private final CircuitBreakerRegistry circuitBreakerRegistry;
    private final RateLimiterRegistry rateLimiterRegistry;

    @PostConstruct
    public void postConstruct() {

        //  注册 Retry 事件监听器
        Retry retry = retryRegistry.retry("retryService");
        retry.getEventPublisher()
                .onEvent(event -> log.info("Retry event: {}", event));

        // 注册 CircuitBreaker 事件监听器
        CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("circuitbreakerService");
        circuitBreaker.getEventPublisher()
                .onEvent(event -> log.info("CircuitBreaker Event: {}", event));

        // 注册 RateLimiter 事件监听器
        RateLimiter rateLimiter = rateLimiterRegistry.rateLimiter("ratelimiterService");
        rateLimiter.getEventPublisher()
                .onEvent(event -> log.info("RateLimiter Event: {}", event));

        // 注册 TimeLimiter 事件监听器
        TimeLimiter timeLimiter = timeLimiterRegistry.timeLimiter("timeoutService");
        timeLimiter.getEventPublisher()
                .onEvent(event -> log.info("TimeLimiter Event: {}", event));
    }
}