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

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.dtcms.com/a/54355.html

相关文章:

  • 单例模式的五种实现方式
  • 基于BMO磁性细菌优化的WSN网络最优节点部署算法matlab仿真
  • 获取当前页面的 url 参数
  • Ubuntu20.04本地配置IsaacLab 4.5.0的训练环境(一)
  • 安卓基础组件Looper - 02 native层面的剖析
  • 单线程 Redis 如何实现高可用?深入图解主从复制与哨兵模式
  • HuggingFace 模型转换为 GGUF/GGML
  • [MySQL初阶]MySQL(4)基本查询
  • K8s 1.27.1 实战系列(一)介绍及准备工作
  • 使用阿里云 API 进行声音身份识别的方案
  • Pycharm 远程执行无法显示 cv2.imshow() 的原因分析及解决方案
  • wheel_legged_genesis 开源项目复现与问题记录
  • Linux - 进程控制
  • 【极光 Orbit•STC8A-8H】02. STC8 单片机工程模板创建
  • 鸿蒙全栈开发 D1
  • JCRQ1河马算法+四模型对比!HO-CNN-GRU-Attention系列四模型多变量时序预测
  • git-filter-repo 清除大文件教程
  • K8S学习之基础十:k8s中初始化容器和主容器
  • 游戏辅助技术教程【预习课】
  • FPGA-按键消抖
  • 信息安全技术、加密、摘要、签名、PKI(高软41)
  • Java数组详解/从JVM理解数组/数组反转/随机排名/数组在计算机如何存储
  • 【DeepSeek】Ubuntu快速部署DeepSeek(Ollama方式)
  • 2024华为OD机试真题-字符串加密算法(C++)-E卷-100分
  • 机器学习-GBDT算法
  • 数字组合(信息学奥赛一本通-1291)
  • 《深度学习进阶》第7集:深度实战 通过训练一个智能体玩游戏 来洞察 强化学习(RL)与决策系统
  • 全新方案80M/S,告别限速!
  • 阿里云云监控资源告警常用模板
  • 软考架构师笔记-计算机网络