guava-retrying,重试工具使用

来源:互联网 发布:js 实现文档预览功能 编辑:程序博客网 时间:2024/05/29 11:04

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

先上一段实例代码:

 /**     * guava retry     * 结果返回false  重试:固定等待时长为 300 ms,最多尝试 3 次     */    static Retryer<Boolean> retryer = RetryerBuilder.<Boolean>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<Boolean> 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
原创粉丝点击