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

Spring Boot 中使用 Resilience4j 实现弹性微服务的简单了解

1. 引言

在微服务架构中,服务的弹性是非常重要的。Resilience4j 是一个轻量级的容错库,专为函数式编程设计,提供了断路器、重试、舱壁、限流器和限时器等功能。

这里不做过多演示,只是查看一下官方案例并换成maven构建相关展示;

2.配置

spring:application.name: resilience4j-demojackson.serialization.indent_output: true # 格式化输出jsonserver:port: 9080management.endpoints.web.exposure.include: '*' # 暴露所有端点
management.endpoint.health.show-details: always # 显示详细健康信息management.health.diskspace.enabled: false # 关闭磁盘空间健康检查
management.health.db.enabled: false # 关闭数据库健康检查
management.health.circuitbreakers.enabled: true #  开启断路器健康检查
management.health.conditions.enabled: false # 关闭条件健康检查
management.health.ratelimiters.enabled: false # 关闭限流器健康检查info:name: ${spring.application.name}description: resilience4j demoenvironment: ${spring.profiles.active}version: 0.0.1management.metrics.tags.application: ${spring.application.name} # 添加自定义标签
management.metrics.distribution.percentiles-histogram.http.server.requests: true # 开启http请求统计
management.metrics.distribution.percentiles-histogram.resilience4j.circuitbreaker.calls: true # 开启断路器统计#resilience4j.circuitbreaker.metrics.use_legacy_binder: true # 使用旧版绑定器resilience4j.circuitbreaker: # 断路器配置configs:default:registerHealthIndicator: true # 开启健康检查slidingWindowSize: 10 # 滑动窗口大小minimumNumberOfCalls: 5 # 最小调用次数permittedNumberOfCallsInHalfOpenState: 3 # 半开状态最大调用次数automaticTransitionFromOpenToHalfOpenEnabled: true # 自动切换到半开状态waitDurationInOpenState: 5s # 半开状态等待时间failureRateThreshold: 50 # 失败率阈值eventConsumerBufferSize: 10 # 事件消费者缓冲区大小recordExceptions: # 记录异常- org.springframework.web.client.HttpServerErrorException # http服务端错误- java.util.concurrent.TimeoutException # 超时异常- java.io.IOException # IO异常ignoreExceptions: # 忽略异常- io.github.robwin.exception.BusinessException # 业务异常shared: # 共享配置slidingWindowSize: 100 # 滑动窗口大小permittedNumberOfCallsInHalfOpenState: 30 # 半开状态最大调用次数waitDurationInOpenState: 1s # 半开状态等待时间failureRateThreshold: 50 # 失败率阈值eventConsumerBufferSize: 10 # 事件消费者缓冲区大小ignoreExceptions: # 忽略异常- io.github.robwin.exception.BusinessException # 业务异常instances: # 实例配置backendA: # 配置 backendA 实例baseConfig: default # 使用 default 配置backendB: # 配置 backendB 实例registerHealthIndicator: true # 开启健康检查slidingWindowSize: 10 # 滑动窗口大小minimumNumberOfCalls: 10 # 最小调用次数permittedNumberOfCallsInHalfOpenState: 3 # 半开状态最大调用次数waitDurationInOpenState: 5s # 半开状态等待时间failureRateThreshold: 50 # 失败率阈值eventConsumerBufferSize: 10 # 事件消费者缓冲区大小recordFailurePredicate: io.github.robwin.exception.RecordFailurePredicate # 记录异常
resilience4j.retry: # 重试配置configs:default:maxAttempts: 3 # 最大重试次数waitDuration: 100 # 重试间隔时间 (ms)retryExceptions: # 记录异常- org.springframework.web.client.HttpServerErrorException # http服务端错误- java.util.concurrent.TimeoutException # 超时异常- java.io.IOException # IO异常ignoreExceptions: # 忽略异常- io.github.robwin.exception.BusinessException # 业务异常instances:backendA: # 配置 backendA 实例baseConfig: default # 使用 default 配置backendB: # 配置 backendB 实例baseConfig: default # 使用 default 配置
resilience4j.bulkhead: # 舱壁 批量请求配置configs:default:maxConcurrentCalls: 100 # 最大并发调用数instances:backendA: # 配置 backendA 实例maxConcurrentCalls: 10 # 最大并发调用数backendB:maxWaitDuration: 10ms # 最大等待时间maxConcurrentCalls: 20 # 最大并发调用数resilience4j.thread-pool-bulkhead: # 线程池舱壁 批量请求配置configs:default:maxThreadPoolSize: 4 # 最大线程池大小coreThreadPoolSize: 2 # 核心线程池大小queueCapacity: 2 # 队列容量instances:backendA:baseConfig: default # 使用 default 配置backendB:maxThreadPoolSize: 1 # 覆盖默认配置,最大线程池大小coreThreadPoolSize: 1 # 覆盖默认配置,核心线程池大小queueCapacity: 1 # 覆盖默认配置,队列容量resilience4j.ratelimiter: # 限流器配置configs:default:registerHealthIndicator: false # 关闭健康检查limitForPeriod: 10 # 每个周期内的请求限制数limitRefreshPeriod: 1s # 周期刷新时间,即每秒刷新一次timeoutDuration: 0 # 请求超时时间,0表示不超时eventConsumerBufferSize: 100 # 事件消费者缓冲区大小instances:backendA:baseConfig: default # 使用默认配置backendB:limitForPeriod: 6 # 每个周期内的请求限制数limitRefreshPeriod: 500ms # 周期刷新时间,即每500毫秒刷新一次timeoutDuration: 3s # 请求超时时间,3秒resilience4j.timelimiter: # 限时器配置configs:default:cancelRunningFuture: false # 是否取消正在运行的FuturetimeoutDuration: 2s # 超时时间,2秒instances:backendA:baseConfig: default # 使用默认配置backendB:baseConfig: default # 使用默认配置

 3.依赖

 <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.5</version><relativePath/> <!-- lookup parent from repository --></parent><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><resilience4j.version>2.0.2</resilience4j.version></properties><dependencies><!-- Spring Boot Starters --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><!-- Resilience4j --><dependency><groupId>io.github.resilience4j</groupId><artifactId>resilience4j-spring-boot2</artifactId><version>${resilience4j.version}</version></dependency><dependency><groupId>io.github.resilience4j</groupId><artifactId>resilience4j-all</artifactId><version>${resilience4j.version}</version></dependency><dependency><groupId>io.github.resilience4j</groupId><artifactId>resilience4j-reactor</artifactId><version>${resilience4j.version}</version></dependency><!-- Micrometer Prometheus --><dependency><groupId>io.micrometer</groupId><artifactId>micrometer-registry-prometheus</artifactId></dependency><!-- Chaos Monkey for Spring Boot --><dependency><groupId>de.codecentric</groupId><artifactId>chaos-monkey-spring-boot</artifactId><version>2.7.0</version></dependency><!-- Vavr Jackson --><dependency><groupId>io.vavr</groupId><artifactId>vavr-jackson</artifactId><version>0.10.3</version></dependency><!-- Test Dependencies --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>io.projectreactor</groupId><artifactId>reactor-test</artifactId><version>3.4.22</version><scope>test</scope></dependency></dependencies>

 这里正好用Prometheus和Grafana看看效果

4 总结

通过本文的介绍,你应该已经了解了如何在 Spring Boot 项目中配置和使用 Resilience4j 来实现断路器、重试、舱壁、限流器和限时器等功能,Resilience4j 提供了丰富的配置选项和灵活的使用方式,帮助你构建弹性的微服务。

相关文章:

  • 自学鸿蒙HarmonyOS的ArkTS语言<十>@BuilderParam装饰器
  • ERROR: No matching distribution found for execjs
  • 《逻辑006:页面跳转并传参》
  • 麻省理工学院 - MIT - 线性代数学习笔记
  • 【linux】服务器安装NVIDIA驱动
  • 【React笔记初学总结一】React新手的学习流程笔记总结,掰开了揉碎了,下载安装基础结构学习
  • Nginx系列-8 allow与deny和error_page使用介绍
  • 达梦数据库(一)mysql2dm
  • Nvidia Isaac Sim代码编程 入门教程 2024(7)
  • HarmonyOS根据官网写案列~ArkTs从简单地页面开始
  • Spring中的IOC详解
  • docker安装指导
  • 【Day12】登录认证、异常处理
  • 基于JAVA+SpringBoot+Vue+uniapp的微信小程序点餐平台
  • C++案例三:猜数字游戏
  • hexo+github搭建个人博客
  • CODING 缺陷管理功能正式开始公测
  • github指令
  • Golang-长连接-状态推送
  • java架构面试锦集:开源框架+并发+数据结构+大企必备面试题
  • JS 面试题总结
  • JSDuck 与 AngularJS 融合技巧
  • python学习笔记 - ThreadLocal
  • SpringCloud(第 039 篇)链接Mysql数据库,通过JpaRepository编写数据库访问
  • thinkphp5.1 easywechat4 微信第三方开放平台
  • Twitter赢在开放,三年创造奇迹
  • ⭐ Unity 开发bug —— 打包后shader失效或者bug (我这里用Shader做两张图片的合并发现了问题)
  • windows下如何用phpstorm同步测试服务器
  • 分享几个不错的工具
  • 基于Mobx的多页面小程序的全局共享状态管理实践
  • 快速构建spring-cloud+sleuth+rabbit+ zipkin+es+kibana+grafana日志跟踪平台
  • 悄悄地说一个bug
  • 入门到放弃node系列之Hello Word篇
  • 使用 5W1H 写出高可读的 Git Commit Message
  • 责任链模式的两种实现
  • 智能合约Solidity教程-事件和日志(一)
  • nb
  • 【运维趟坑回忆录】vpc迁移 - 吃螃蟹之路
  • linux 淘宝开源监控工具tsar
  • 测评:对于写作的人来说,Markdown是你最好的朋友 ...
  • ​​​【收录 Hello 算法】9.4 小结
  • #使用清华镜像源 安装/更新 指定版本tensorflow
  • #数据结构 笔记三
  • (13):Silverlight 2 数据与通信之WebRequest
  • (二)JAVA使用POI操作excel
  • (二)Pytorch快速搭建神经网络模型实现气温预测回归(代码+详细注解)
  • (附源码)spring boot公选课在线选课系统 毕业设计 142011
  • (附源码)springboot助农电商系统 毕业设计 081919
  • (附源码)计算机毕业设计SSM智慧停车系统
  • (三维重建学习)已有位姿放入colmap和3D Gaussian Splatting训练
  • (游戏设计草稿) 《外卖员模拟器》 (3D 科幻 角色扮演 开放世界 AI VR)
  • (原創) 如何使用ISO C++讀寫BMP圖檔? (C/C++) (Image Processing)
  • (轉貼) 寄發紅帖基本原則(教育部禮儀司頒布) (雜項)
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • .equal()和==的区别 怎样判断字符串为空问题: Illegal invoke-super to void nio.file.AccessDeniedException