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

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

有很多可以借鉴的地方,

https://www.cnblogs.com/onlychang92/p/5203139.html

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值