当前位置: 首页 > article >正文

Spring Boot整合Resilience4j教程

精心整理了最新的面试资料和简历模板,有需要的可以自行获取

点击前往百度网盘获取
点击前往夸克网盘获取

以下是将Spring Boot与Resilience4j整合的详细教程,包含基础配置和核心功能示例:


Spring Boot整合Resilience4j教程

Resilience4j提供容错机制(断路器、重试、限流等),帮助构建弹性微服务。


一、环境准备
  1. 创建项目
    使用Spring Initializr生成项目,选择:

    • Spring Boot 3.x
    • 依赖:Spring Web, Spring Actuator, Lombok
  2. 添加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)
  1. 定义Service类

    @Service
    public class ExternalService {
        
        // 模拟外部服务调用
        public String callExternalService() {
            if (Math.random() > 0.5) {
                throw new RuntimeException("External service error");
            }
            return "Success";
        }
    }
    
  2. 添加断路器逻辑

    @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";
    }
}

五、监控与端点
  1. 启用Actuator端点
    application.yml

    management:
      endpoints:
        web:
          exposure:
            include: health,circuitbreakers,retries
    
  2. 访问监控信息

    • 断路器状态:http://localhost:8080/actuator/health
    • 所有断路器:http://localhost:8080/actuator/circuitbreakers
    • 重试信息:http://localhost:8080/actuator/retries

六、测试断路器行为
  1. 快速失败触发
    连续发送多个请求,让超过50%的请求失败:

    curl http://localhost:8080/api/data
    
  2. 观察断路器状态
    当失败率达到阈值后,后续请求直接进入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")


八、常见问题
  1. 注解不生效
    确保添加了@EnableAspectJAutoProxy或在启动类添加:

    @SpringBootApplication
    @EnableCircuitBreaker  // 对于旧版本可能需要
    public class Application { ... }
    
  2. 版本兼容性
    Spring Boot 3.x需使用Resilience4j 2.x+,检查依赖版本匹配。


完成以上步骤后,您的Spring Boot应用已具备弹性容错能力。建议通过单元测试和压力测试验证不同故障场景下的系统行为。


http://www.kler.cn/a/574165.html

相关文章:

  • 大模型基础-深度解析-什么是语言模型及大模型相关历史回顾
  • Unity帧同步与状态同步混合架构开发指南
  • python之爬虫入门实例
  • 永恒之塔鼠标卡顿移动鼠标卡屏的问题
  • 高考數學。。。
  • 0.QT概述|下载|配置环境
  • dify 工作流 迭代
  • Anolis服务器Arm64架构服务器配置(其他版本服务器解决方式思路一质)
  • C++海康相机DEMO
  • Ubuntu 安装docker docker-compose
  • 5.训练策略:优化深度学习训练过程的实践指南——大模型开发深度学习理论基础
  • 安装remixd,在VScode创建hardhat
  • Java面经
  • 微电网协调控制器ACCU-100 分布式光伏 光储充一本化
  • 软件高级架构师 - 软件工程
  • 【人工智能】数据挖掘与应用题库(501-600)
  • 持久蠕变交替(C环)应力腐蚀试验机
  • 在Java实际项目中什么情况才会使用到消息队列?
  • JVM与性能调优详解
  • 【北京迅为】iTOP-RK3568OpenHarmony系统南向驱动开发GPIO基础知识