|
1 | 1 | package com.github.cadecode.uniboot.framework.config; |
2 | 2 |
|
| 3 | +import com.github.cadecode.uniboot.framework.exception.RetryableException; |
3 | 4 | import org.springframework.context.annotation.Bean; |
4 | 5 | import org.springframework.context.annotation.Configuration; |
5 | 6 | import org.springframework.context.annotation.Primary; |
6 | 7 | import org.springframework.retry.annotation.EnableRetry; |
7 | | -import org.springframework.retry.backoff.ExponentialBackOffPolicy; |
8 | | -import org.springframework.retry.policy.SimpleRetryPolicy; |
9 | 8 | import org.springframework.retry.support.RetryTemplate; |
10 | 9 |
|
11 | 10 | /** |
|
19 | 18 | public class RetryConfig { |
20 | 19 |
|
21 | 20 | /** |
22 | | - * 重试模板,重试三次 |
| 21 | + * 默认重试模板,所有异常类型 |
| 22 | + * 重试 5 次,间隔 1 秒,每次间隔时间 x2 |
23 | 23 | */ |
24 | 24 | @Primary |
25 | 25 | @Bean |
26 | | - public RetryTemplate retryTemplate3Times() { |
27 | | - RetryTemplate retryTemplate = new RetryTemplate(); |
28 | | - SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(); |
29 | | - simpleRetryPolicy.setMaxAttempts(3); |
30 | | - retryTemplate.setRetryPolicy(simpleRetryPolicy); |
31 | | - // 延迟规则 |
32 | | - // 初次重试间隔 1 秒,后面每次乘以 2 |
| 26 | + public RetryTemplate retryTemplate() { |
| 27 | + /* |
| 28 | + SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); |
| 29 | + retryPolicy.setMaxAttempts(3); |
33 | 30 | ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy(); |
34 | 31 | backOffPolicy.setInitialInterval(1000L); |
| 32 | + backOffPolicy.setMaxInterval(10000L); |
35 | 33 | backOffPolicy.setMultiplier(2); |
| 34 | + RetryTemplate retryTemplate = new RetryTemplate(); |
| 35 | + retryTemplate.setRetryPolicy(retryPolicy); |
36 | 36 | retryTemplate.setBackOffPolicy(backOffPolicy); |
37 | | - return retryTemplate; |
| 37 | + */ |
| 38 | + |
| 39 | + // 使用 builder 模式代替以上代码 |
| 40 | + return RetryTemplate.builder() |
| 41 | + .maxAttempts(5) |
| 42 | + .retryOn(Exception.class) |
| 43 | + .exponentialBackoff(1000L, 2, 30000L) |
| 44 | + .build(); |
38 | 45 | } |
39 | 46 |
|
| 47 | + /** |
| 48 | + * 指定异常类型的重试模板,只重试异常类型或异常 cause 为 RetryableException |
| 49 | + * 通过抛出 RetryableException 实现自定义控制重试逻辑 |
| 50 | + * 重试 5 次,间隔 1 秒,每次间隔时间 x2 |
| 51 | + */ |
| 52 | + @Bean |
| 53 | + public RetryTemplate retryTemplateOnRetryable() { |
| 54 | + return RetryTemplate.builder() |
| 55 | + .maxAttempts(5) |
| 56 | + .retryOn(RetryableException.class) |
| 57 | + // 开启 cause 穿透,可根据 cause 判断 |
| 58 | + .traversingCauses() |
| 59 | + .exponentialBackoff(1000L, 2, 30000L) |
| 60 | + .build(); |
| 61 | + } |
40 | 62 | } |
0 commit comments