1.spring-retry
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.4.RELEASE</version>
</dependency>
@EnableRetry
public class WeChatApplication {
public static void main(String[] args) {
SpringApplication.run(WeChatApplication.class, args);
}
AtomicInteger num = new AtomicInteger(0);
@GetMapping("ceshi")
@Retryable(value = {Exception.class}, maxAttempts = 4, backoff = @Backoff(delay = 1000, maxDelay = 2))
public Object test() {
System.out.println("次数" + num.incrementAndGet());
int a = 1 / 0;
return BaseResult.success(a);
}
}
2.guava-retrying
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
@Test
public void t() {
Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
.retryIfException()
.withStopStrategy(StopStrategies.stopAfterDelay(30, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.withWaitStrategy(WaitStrategies.incrementingWait(1, TimeUnit.SECONDS, 0, TimeUnit.SECONDS))
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
if (attempt.hasException()) {
System.out.println("进入重试回调");
}
}
}).build();
try {
retryer.call(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int i = 1 / 0;
System.out.println("重试");
return 0;
}
});
} catch (ExecutionException e) {
System.out.println("ExecutionException");
} catch (RetryException e) {
System.out.println("RetryException");
}
}
@Test
public void t2() {
Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
.retryIfResult(result -> result != 1)
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.withWaitStrategy(WaitStrategies.incrementingWait(1, TimeUnit.SECONDS, 0, TimeUnit.SECONDS))
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
if (attempt.hasException()) {
System.out.println("进入重试回调");
}
}
}).build();
try {
retryer.call(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("重试");
return 1;
}
});
} catch (ExecutionException e) {
System.out.println("ExecutionException");
} catch (RetryException e) {
System.out.println("RetryException");
}
}
本文由 GY 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2022/08/30 10:52