您的位置:首页 > 其它

Guava retryer优雅的实现接口重调机制

2018-03-22 19:47 369 查看
今天遇到一个问题,在调用第三方接口的时候,会遇到断网、获取不到数据等各种异常信息,需要对该信息进行分析,然后进行接口的重新调用,通过网上找资料,使用的谷歌的一个插件,使用Guava retryer进行接口的重调,具体见代码。package com.yooyii.qdp.test;

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

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 com.google.common.base.Predicates;

import lombok.extern.slf4j.Slf4j;
import net.dongliu.requests.Requests;

@Slf4j
public class GuavaRetry {

static Retryer<String> retryer;

static int count = 0;

static {
retryer = RetryerBuilder.<String>newBuilder().retryIfResult(Predicates.equalTo("")) // 返回false时重试
.withWaitStrategy(WaitStrategies.fixedWait(1000, TimeUnit.MILLISECONDS)) // 1000ms后重试
.withStopStrategy(StopStrategies.stopAfterAttempt(20)) // 重试20次后停止
.build();
}

public static void main(String[] args) throws InterruptedException {
sendSMS();
}

public static String sendSMS() {

try {
return retryer.call(new Callable<String>() {
@Override
public String call() thro
4000
ws Exception {
//
count++;
//
String res = "";
try {
res = Requests.get("https://www.baidu.com/").send().readToText();
} catch (Exception e) {
log.debug(e.getMessage());
}
log.debug(count + "--" + String.valueOf(res.length()));
//
return res;
}
});
} catch (Exception e) {
return "";
}
}
}
这个方法可以修改为一个通用的工具类,进行多数接口的重调机制判断。
大家可以参考以下两个人的:
https://www.cnblogs.com/jianzh5/p/6651799.html

http://blog.csdn.net/aitangyong/article/details/53840719

有很多可以借鉴的地方,
https://www.cnblogs.com/onlychang92/p/5203139.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: