默认实现超时3次后重试
public class RpcExecutor {
/**
* 最大重试次数
*/
private static final Integer MAX_RETRY_NO = 3;
/**
* 执行rpc 方式
* @param execute execute 方法
* @param <T> 返回类型
* @return 方法返回值
*/
public <T> T doExecuteRpc(Execute<T> execute, Object... params) {
Integer reTryNo = 0;
while (reTryNo <= MAX_RETRY_NO) {
try {
log.info("param: " + obtainParamStr(params));
T res = execute.doCall();
log.info("response: " + JSON.toJSONString(res));
return res;
} catch (Exception e) {
reTryNo ++;
if(reTryNo >= MAX_RETRY_NO) {
throw new RuntimeException(e);
}
}
}
return null;
}
/**
* 参数拼接
* @param params
* @return
*/
private StringBuilder buildParam(Object[] params) {
StringBuilder sb = new StringBuilder("");
if (params != null) {
for (Object param : params) {
sb.append(JSON.toJSONString(param)).append(",");
}
}
return sb;
}
/**
* 函数式接口
* @param <T> 返回类型
*/
public interface Execute<T> {
T doCall() throws Exception;
}
}