guava-retrying重试工具库: 什么时候终止

当我们重试到一定阶段的时候,需要终止重试过程,比如重试了n次或者重试了n秒等。


StopStrategies.stopAfterAttempt(n):在重试了n次后终止,这个实际中最常用。

import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public class TestStop {

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

    private static Callable<Void> task = new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            System.out.println(df.format(new Date()));
            throw new RuntimeException();
        }
    };

    public static void main(String[] args) throws Exception {
        // 每次间隔1s后重试
        Retryer<Void> retryer = RetryerBuilder.<Void>newBuilder()
                .retryIfException()
                .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                //.withStopStrategy(StopStrategies.neverStop())
                //.withStopStrategy(StopStrategies.stopAfterDelay(10, TimeUnit.SECONDS))
                .build();

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

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

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


StopStrategies.neverStop():从不终止,一直重试,没有什么实际用处。


StopStrategies.stopAfterDelay(10, TimeUnit.SECONDS):一直重试,指定时间过后终止。


guava-retrying提供了StopStrategy接口,我们可以实现自己想要的终止逻辑。


import com.github.rholder.retry.Attempt;
import com.github.rholder.retry.StopStrategy;

public class MyStopStrategy implements StopStrategy {

    private int attemptCount;

    public MyStopStrategy() {
        this.attemptCount = (int) Math.floor(Math.random() * 10) + 1;
        System.out.println("重试" + attemptCount + "后终止");
    }


    @Override
    public boolean shouldStop(Attempt failedAttempt) {
        return failedAttempt.getAttemptNumber() == attemptCount;
    }
}


下面我们使用自己实现的终止策略,重试1~11间的随机次数后终止。
Retryer<Void> retryer = RetryerBuilder.<Void>newBuilder()
		.retryIfException()
		.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
		.withStopStrategy(new MyStopStrategy())
		.build();
try {
	retryer.call(task);
} catch (Exception e) {
	System.err.println("still failed after retry." + e.getCause().toString());
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值