guava-retrying,重试工具使用

最常用的就是在方法抛出异常的时候重试,比如网络故障导致的IOException。java异常系统分为:runtime异常,checked异常和error,其中ERROR程序处理不了,不需要管;不过作为学习,我们可以测试下error的情况。下面这段代码我们定义了3个任务:分别抛出runtime异常、checked异常、error。

先上一段实例代码:

 /**
     * guava retry
     * 结果返回false  重试:固定等待时长为 300 ms,最多尝试 3 次
     */
    static Retryer retryer = RetryerBuilder.newBuilder()
            .retryIfExceptionOfType(RestClientException.class)
            .retryIfResult(aBoolean -> Objects.equals(aBoolean, false))
            .withWaitStrategy(WaitStrategies.fixedWait(300, TimeUnit.MILLISECONDS))
            .withStopStrategy(StopStrategies.stopAfterAttempt(3))
            .build();
调用:

for (final String mobile : Mobiles) {
            final SmsLog smsLog = new SmsLog(mobile, content);

            Callable sendTask = () -> send(mobile, content);
            try {
                retryer.call(sendTask);
            } catch (ExecutionException | RetryException e) {
                logger.error("重试三次,发送短信失败");
            }
        }
private Boolean send(String mobile, String content) {
        boolean success = true;
        .....
        return success;
    }


在这里加入使用详细介绍:http://blog.csdn.net/aitangyong/article/details/53886293

你可能感兴趣的:(系统架构)