spring cloud resilience4j-retry 重试

博客介绍了Spring Cloud Resilience4j相关内容,包括参数说明、配置文件和代码。阐述了组件执行顺序,Retry最后执行。还提及了spring cloud resilience4j - retry重试、Bulkhead线程隔离并发控制、CircuitBreaker熔断器、RateLimiter流控等功能。

参数说明

属性默认值说明
maxAttempts3最大重试次数(包含最初的第一次调用)
waitDuration500[ms]固定的重试间隔
intervalFunctionnumOfAttempts -> waitDuration计算重试等待时间的函数,默认为固定值
retryOnResultPredicateresult -> false配置某个结果是否要重试
retryOnExceptionPredicatethrowable -> true配置某个异常是否要重试
retryExceptionsempty要重试的异常列表,包含子类型
ignoreExceptionsempty忽略的异常列表,包含子类型

配置文件

resilience4j.retry:
    instances:
        backendA:
            maxRetryAttempts: 3
            waitDuration: 10s
            enableExponentialBackoff: true
            exponentialBackoffMultiplier: 2
            retryExceptions:
                - org.springframework.web.client.HttpServerErrorException
                - java.io.IOException
            ignoreExceptions:
                - io.github.robwin.exception.BusinessException
        backendB:
            maxRetryAttempts: 3
            waitDuration: 10s
            retryExceptions:
                - org.springframework.web.client.HttpServerErrorException
                - java.io.IOException
            ignoreExceptions:
                - io.github.robwin.exception.BusinessException

代码

@CircuitBreaker(name = "backendA", fallbackMethod = "fallback")
@RateLimiter(name = "backendA")
@Bulkhead(name = "backendA")
@Retry(name = "backendA", fallbackMethod = "fallback")
@TimeLimiter(name = "backendA")
public Mono<String> method(String param1) {
    return Mono.error(new NumberFormatException());
}

private Mono<String> fallback(String param1, IllegalArgumentException e) {
    return Mono.just("test");
}

private Mono<String> fallback(String param1, RuntimeException e) {
    return Mono.just("test");
}

执行顺序:

Retry ( CircuitBreaker ( RateLimiter ( TimeLimiter ( Bulkhead ( Function ) ) ) ) )

Retry是最后执行

更多

spring cloud resilience4j-retry 重试
spring cloud resilience4j - Bulkhead 线程隔离 并发控制
spring cloud Resilience4j - 熔断器 CircuitBreaker
spring cloud resilience4j - RateLimiter 流控

https://resilience4j.readme.io/docs/retry

### Spring Cloud Resilience4J 配置详解及 Hystrix 到 Resilience4J 的迁移 以下是关于如何将 Hystrix 配置迁移到 Resilience4J 的详细解析以及 Spring Cloud Resilience4J 的配置说明。 --- #### 1. **Hystrix Resilience4J 的对比** 尽管两者都用于处理微服务中的容错弹性问题,但在设计理念上有显著差异。Resilience4J 是一种轻量级库,专注于模块化设计,提供独立的子组件(如熔断器、限流器等),而 Hystrix 提供了一个全面的解决方案[^1]。 --- #### 2. **Spring Cloud Resilience4J 基本概念** Resilience4J 提供了多个核心功能模块,包括但不限于: - **Circuit Breaker**: 自动检测失败的服务调用并阻止进一步请求。 - **Rate Limiter**: 控制每秒允许的最大请求数。 - **Retry**: 处理临时错误并通过重试恢复连接。 - **Bulkhead**: 类似于信号量隔离,限制并发请求数。 以下是一个典型的 Resilience4J 配置结构: ```yaml resilience4j: circuitbreaker: configs: default: registerHealthIndicator: true slidingWindowSize: 10 minimumNumberOfCalls: 5 permittedNumberOfCallsInHalfOpenState: 3 automaticTransitionFromOpenToHalfOpenEnabled: true waitDurationInOpenState: 10s failureRateThreshold: 50 recordExceptions: - java.io.IOException - org.springframework.web.client.HttpServerErrorException ignoreExceptions: - com.example.MyCustomException instances: myService: baseConfig: default ``` 在此配置中: - `slidingWindowSize`: 定义滑动窗口大小,即统计最近多少次调用来计算成功率/失败率。 - `failureRateThreshold`: 设置触发熔断的失败率阈值。 - `waitDurationInOpenState`: 熔断打开后等待的时间间隔,之后尝试半开状态。 --- #### 3. **从 Hystrix 到 Resilience4J 的迁移** 假设原始 Hystrix 配置如下: ```yaml hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 30000 semaphore: maxConcurrentRequests: 1000 ``` 对应的 Resilience4J 配置可以这样转换: ##### (1)**超时设置** Hystrix 的 `timeoutInMilliseconds` 映射到 Resilience4J 的 `timeout.duration`: ```yaml resilience4j: timeout: instances: default: timeoutDuration: 30s ``` ##### (2)**最大并发请求数** Hystrix 的 `maxConcurrentRequests` 可以通过 Bulkhead 实现: ```yaml resilience4j: bulkhead: instances: default: maxConcurrentCalls: 1000 maxWaitDuration: 0ms # 不启用排队机制 ``` ##### (3)**熔断器配置** 如果需要实现类似于 Hystrix 的熔断功能,可使用 Resilience4J 的 Circuit Breaker: ```yaml resilience4j: circuitbreaker: instances: myService: slidingWindowSize: 10 minimumNumberOfCalls: 5 failureRateThreshold: 50 waitDurationInOpenState: 10s automaticTransitionFromOpenToHalfOpenEnabled: true ``` --- #### 4. **代码示例** 以下是一个结合 Resilience4J 注解的方式实现服务调用的例子: ```java import io.github.resilience4j.bulkhead.annotation.Bulkhead; import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker; import io.github.resilience4j.retry.annotation.Retry; @Service public class MyService { @CircuitBreaker(name = "myService", fallbackMethod = "fallback") @Bulkhead(name = "default") @Retry(name = "retryMyService") public String callExternalService() { return restTemplate.getForObject("http://external-service/api", String.class); } public String fallback(Exception e) { return "Fallback response due to exception: " + e.getMessage(); } } ``` 在这个例子中: - `@CircuitBreaker`: 添加熔断保护。 - `@Bulkhead`: 控制并发请求数。 - `@Retry`: 在发生暂时性错误时自动重试--- #### 5. **复杂弹性策略** 当需要组合多种弹性策略时,可以在同一个方法上叠加多个注解。例如,下面的配置实现了熔断器、限流器重试的联合使用[^3]: ```yaml resilience4j: circuitbreaker: instances: complexStrategy: slidingWindowSize: 10 failureRateThreshold: 50 waitDurationInOpenState: 10s ratelimiter: instances: complexStrategy: limitForPeriod: 100 limitRefreshPeriod: 1s retry: instances: complexStrategy: maxAttempts: 3 waitDuration: 2s ``` 对应的方法签名如下: ```java @CircuitBreaker(name = "complexStrategy", fallbackMethod = "fallback") @RateLimiter(name = "complexStrategy") @Retry(name = "complexStrategy") public String performComplexOperation() { // Service logic here } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiegwei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值