You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

46 lines
1.5 KiB

package com.woniu.retry;
import com.github.rholder.retry.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
//Guava Retry重试原来这么简单!根据返回值判断是否需要重试!
@Slf4j
public class GuavaRetryTest {
private Integer num = 1;
@Test
public void guavaRetry() {
Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
//无论出现什么异常,都进行重试
.retryIfException()
//返回结果为 error时,进行重试
.retryIfResult(result -> Objects.equals(result, "error"))
//重试等待策略:等待 2s 后再进行重试
.withWaitStrategy(WaitStrategies.fixedWait(2, TimeUnit.SECONDS))
//重试停止策略:重试达到 3 次
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
System.out.println("RetryListener: 第" + attempt.getAttemptNumber() + "次调用");
}
})
.build();
try {
retryer.call(() -> testGuavaRetry());
} catch (Exception e) {
e.printStackTrace();
}
}
private String testGuavaRetry() {
log.info("重试次数:{}", num++);
return "error";
}
}