guava-retrying 包有一个重试工具,这便是重试示例代码,同时,参考文章有 https://cloud.tencent.com/developer/article/1752086

引入 maven

1
2
3
4
5
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>

封装为工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class RetryUtil {
private RetryUtil(){}

public static final Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
//重试条件
.retryIfResult(aBoolean -> Objects.equals(aBoolean,false))
//等待策略,此处为120秒重试一次
.withWaitStrategy(WaitStrategies.fixedWait(150, TimeUnit.SECONDS))
//停止策略,此处只重试10次
.withStopStrategy(StopStrategies.stopAfterAttempt(10))
.build();
}
````

测试

```java
@Slf4j
public class TestUtils {

@Test
void context() throws ExecutionException, RetryException {
AtomicInteger j = new AtomicInteger();
RetryUtil.retryer.call(() -> {
log.info("start {} calculate",j.get());
int i = j.get();
if (i < 8){
j.getAndIncrement();
return false;
}
return true;
});
}
}
Edited on Views times