guava-retrying重试工具库: AttemptTimeLimiter

AttemptTimeLimiter和guava的TimeLimiter基本是一样的,是为了限制某个任务的执行时间。比如我希望一个Callable任务执行时间不超过5s,如果超过抛异常TimeoutException。

import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public class TestTimeLimiter {

    public static void main(String[] args) throws Exception {
        TimeLimiter timeLimiter = new SimpleTimeLimiter();

        timeLimiter.callWithTimeout(buildTask(), 5, TimeUnit.SECONDS, false);
    }

    private static Callable buildTask() {
        return new Callable() {
            @Override
            public Boolean call() throws Exception {
                long start = System.currentTimeMillis();
                long end = start;
                while (end - start <= 10 * 1000) {
                    end = System.currentTimeMillis();
                }

                return true;
            }
        };
    }
}
guava-retrying重试工具库: AttemptTimeLimiter_第1张图片


AttemptTimeLimiter功能与之类似,保证某次重试的执行时间不超过特定值。

public class TestLimit {

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

    public static void main(String[] args) throws Exception {

        Retryer retryer = RetryerBuilder.newBuilder()
                .retryIfException()
                .retryIfResult(Predicates.equalTo(false))
                .withAttemptTimeLimiter(AttemptTimeLimiters.fixedTimeLimit(1, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(5))
                .build();

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

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

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

    }

    private static Callable buildTask() {
        return new Callable() {
            @Override
            public Boolean call() throws Exception {
                System.out.println("called");
                long start = System.currentTimeMillis();
                long end = start;
                while (end - start <= 10 * 1000) {
                    end = System.currentTimeMillis();
                }

                return true;
            }
        };
    }

}
guava-retrying重试工具库: AttemptTimeLimiter_第2张图片


你可能感兴趣的:(分布式系统)