今天遇到一个问题,在调用第三方接口的时候,会遇到断网、获取不到数据等各种异常信息,需要对该信息进行分析,然后进行接口的重新调用,通过网上找资料,使用的谷歌的一个插件,使用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() throws 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
有很多可以借鉴的地方,