請求重試

該代碼就是普通的嘗試五次請求,並無對請求的時間間隔進行限制spring

在邏輯代碼裏能夠加入請求時間的間隔。json

package com.qdsg.ylt_vedio.common.untils;ide

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.RecoveryCallback;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;code

/**
* @Description
* @ClassName ReTryUtil
* @Authetr CZQ
* @Date 2018/9/20 8:38
* @VERSION 1.0
**/
public class ReTryUtil {
private static final Logger logger = LoggerFactory.getLogger(ReTryUtil.class);ip

public static Object doIs(String uri, Object user, Object param) {get

// 重試機制
RetryTemplate oRetryTemplate = new RetryTemplate();
SimpleRetryPolicy oRetryPolicy = new SimpleRetryPolicy();
oRetryPolicy.setMaxAttempts(5);// 重試5次
oRetryTemplate.setRetryPolicy(oRetryPolicy);
Object obj = null;
try {
// obj爲doWithRetry的返回結果,能夠爲任意類型
obj = oRetryTemplate.execute(new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {// 開始重試
String redo = Redo(uri, user, param);
return redo;//這裏是咱們處理的邏輯
}
}, new RecoveryCallback<Object>() {
@Override
public Object recover(RetryContext context) throws Exception { // 重試屢次後都失敗了
return "系統異常,不能結束會議";
}
});
} catch (Exception e) {
logger.error("重試結束會議異常 {}", e.getMessage());
}
return obj;
}it

private static String Redo(String uri, Object user, Object param) {
String str = HttpClientUtil.httpPostRequest(uri, user, param);
JSONObject jsonObject = JSON.parseObject(str);
String code = jsonObject.get("code").toString();
if (code.equals("200")) {
return str;
} else {
logger.info("重試5次,仍然沒有結束掉會議");
throw new RuntimeException();
}
}
}io

相關文章
相關標籤/搜索