guava-retrying重试工具库: 隔多长时间重试

Guava Retrying 提供了 WaitStrategy 接口用于控制重试之间的等待时间,如 noWait(), fixedWait(), randomWait() 和 fibonacciWait() 等。这些策略在 WaitStrategies 类中定义,包括立即重试、固定间隔、随机间隔和斐波那契递增等待等。exponentialWait 则按照指数递增的方式进行等待。测试代码展示了不同策略在重试间隔上的应用效果。" 105348604,9449952,使用Android Studio开发简易计算器,"['Android开发', '计算器应用', '编程问题']
摘要由CSDN通过智能技术生成

guava-retrying提供了WaitStrategy接口,用来控制2次重试的时间间隔,这个接口与StopStrategy有的类似。内置的等待策略在WaitStrategies中定义。


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;

public class AlwaysExceptionTask implements Callable<Boolean> {

    private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
    private int times = 1;

    @Override
    public Boolean call() throws Exception {
        System.out.println(df.format(new Date()));
        int thisTimes = times;
        times++;

        if (thisTimes == 1) {
            throw new NullPointerException();
        } else if (thisTimes == 2) {
            throw new IOException();
        } else if (thisTimes == 3) {
            throw new ArithmeticException();
        } else {
            throw new Exception();
        }
    }
}


WaitStrategies.noWait()失败后立刻重试,没有等待时间。

Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
		.retryIfException()
		.withWaitStrategy(WaitStrategies.noWait())
		.build();

System.out.println("begin..." + df.format(new Date()));

try {
	retryer.call(new AlwaysExceptionTask());
} catch (Exception e) {
	System.err.println("still failed after retry." + e.getCause().toString());
}

System.out.println("end..." + df.format(new Date()));


WaitStrategies.fixedWait(1, TimeUnit.SECONDS)间隔固定时间之后重试,比如每隔1s重试一次。

Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
		.retryIfException()
		.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
		.build();

System.out.println("begin..." + df.format(new Date()));

try {
	retryer.call(new AlwaysExceptionTask());
} catch (Exception e) {
	System.err.println("still failed after retry." + e.getCause().toString());
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值