Guava-retry,java重试组件

使用场景

在日常开发中,我们经常会遇到需要调用外部服务和接口的场景。外部服务对于调用者来说一般都是不可靠的,尤其是在网络环境比较差的情况下,网络抖动很容易导致请求超时等异常情况,这时候就需要使用失败重试策略重新调用 API 接口来获取。重试策略在服务治理方面也有很广泛的使用,通过定时检测,来查看服务是否存活。

Guava Retrying 是一个灵活方便的重试组件,包含了多种的重试策略,而且扩展起来非常容易。

用作者的话来说:

This is a small extension to Google’s Guava library to allow for the creation of configurable retrying strategies for an arbitrary function call, such as something that talks to a remote service with flaky uptime.

使用 Guava-retrying 你可以自定义来执行重试,同时也可以监控每次重试的结果和行为,最重要的基于 Guava 风格的重试方式真的很方便。

网上关于guava-retrying的介绍很多,我就不赘述了,这里有一篇写的比较好的文章:

Guava-retry: 基于 guava 的重试组件

在此基础上我封装了一个Util:

/**
 * Created by [email protected] on 18-7-12.
 */
@Log4j2
public class RetryUtil {

    //出现异常则执行重试,每次任务执行最长执行时间限定为 3 s,重试间隔时间初始为 3 s,最多重试 10秒,随着重试次数的增加每次递增 1 s,每次重试失败,打印日志;
    public static <T> Retryer<T> getADefaultRetryer() {
        Retryer<T> retryer = RetryerBuilder.<T>newBuilder()
            .retryIfException()
            .withStopStrategy(
                StopStrategies.stopAfterDelay(10, TimeUnit.SECONDS))
            .withWaitStrategy(
                WaitStrategies.incrementingWait(3, TimeUnit.SECONDS, 1, TimeUnit.SECONDS))
            .withAttemptTimeLimiter(
                AttemptTimeLimiters.fixedTimeLimit(3, TimeUnit.SECONDS))
            .withRetryListener(new RetryListener() {
                @Override
                public <V> void onRetry(Attempt<V> attempt) {
                    log.debug("retry time = " + attempt.getAttemptNumber());
                    if (attempt.hasException()) {
                        log.error("try failed", attempt.getExceptionCause());
                    }
                }
            })
            .build();

        return retryer;
    }

    // Todo 可以定制参数
}

使用方法仅需一句话:

RetryUtil.<String>getADefaultRetryer()
            .call(() -> getClient().getDataById(id));

猜你喜欢

转载自www.cnblogs.com/acbingo/p/9301654.html