重试机制自己实现

摘要:
packagecom.answern.ceis.web.system.util;/***Createdbywangyong**@Date:2018/10/29.*@Description:*/importlombok.extern.slf4j.Slf4j;importokhttp3.Interceptor;importokhttp3.Request;importokhttp3.Response;i
package com.answern.ceis.web.system.util;
/**
* Created by wangyong
*
* @Date: 2018/10/29.
* @Description:
*/
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.io.InterruptedIOException;
/**
* User: Administrator
* Date: 2017/9/19
* Description:
*/
@Slf4j
public class MyOkHttpRetryInterceptor implements Interceptor {
public int executionCount;//最大重试次数
private long retryInterval;//重试的间隔
MyOkHttpRetryInterceptor(Builder builder) {
this.executionCount = builder.executionCount;
this.retryInterval = builder.retryInterval;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = doRequest(chain, request);
int retryNum = 1;
while ((response == null || !response.isSuccessful()) && retryNum <= executionCount) {
log.info("第{}次重试", retryNum);
final long nextInterval = getRetryInterval();
try {
log.info("等待{}发起回调", nextInterval);
Thread.sleep(nextInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException();
}
// retry the request
log.info("第{}次回调开始", retryNum);
response = doRequest(chain, request);
retryNum++;
}
return response;
}
private Response doRequest(Chain chain, Request request) {
Response response = null;
try {
response = chain.proceed(request);
} catch (Exception e) {
}
return response;
}
/**
* retry间隔时间
*/
public long getRetryInterval() {
return this.retryInterval;
}
public static final class Builder {
private int executionCount;
private long retryInterval;
public Builder() {
executionCount = 3;
retryInterval = 1000;
}
public MyOkHttpRetryInterceptor.Builder executionCount(int executionCount) {
this.executionCount = executionCount;
return this;
}
public MyOkHttpRetryInterceptor.Builder retryInterval(long retryInterval) {
this.retryInterval = retryInterval;
return this;
}
public MyOkHttpRetryInterceptor build() {
return new MyOkHttpRetryInterceptor(this);
}
}
}
package com.answern.ceis.web.system.util;
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* Created by wangyong
*
* @Date: 2018/10/29.
* @Description:
*/
@Component("httpClientByW")
public class HttpClient {
public String okPost(String url, String json) throws IOException {
MyOkHttpRetryInterceptor myOkHttpRetryInterceptor = new MyOkHttpRetryInterceptor.Builder()
.executionCount(3)
.retryInterval(2000)
.build();
OkHttpClient okHttpClient= new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.addInterceptor(myOkHttpRetryInterceptor)
.connectionPool(new ConnectionPool())
.connectTimeout(20000, TimeUnit.MILLISECONDS)
.readTimeout(10000, TimeUnit.MILLISECONDS)
.build();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
}
}

package com.answern.ceis.web.system.controller;
import com.answern.ceis.base.bean.VO.Msg;
import com.answern.ceis.web.system.util.HttpClient;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
/**
* Created by wangyong
*
* @Date: 2018/10/29.
* @Description:
*/
@RestController("ok")
@Api("http测试")
public class OkHttpClientController {
private static final Logger logger = LoggerFactory.getLogger(EmailController.class);
@Autowired
HttpClient httpClient;
@PostMapping("okhttp")
@Async
public Msg sendEmail() throws Exception {
Msg msg = new Msg();
String url = "https://testopr.tairanbaoxian.com/api/product/thirdPartInterface/interfaceChannel";
String json = "";
try {
String response = httpClient.okPost(url,json);
logger.info("返回信息为{}",response);
msg.setCode(0);
msg.setMessage(response);
} catch (IOException e) {
e.printStackTrace();
}
return msg;
}
}
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.11.0</version>
</dependency>

免责声明:文章转载自《重试机制自己实现》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇使用正则表达式来截取nginx中的内置变量Chrome浏览器下调试SASS下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

com.aliyun.openservices.shade.com.alibaba.fastjson.JSONException: exepct '[', but {, pos 1, line 1, column 2

错误报告的原因:您放置了一个非List对象,但希望从packagetest中取出List对象;导入java.text。SimpleDateFormat;导入java.util。阵列列表;导入java.util。日期导入java.util。列表importcom.alibaba.fastjson。JSON;导入com.alibaba.fastj...

【转】MUD教程--巫师入门教程4

在MUD中,为了解决定时触发某种现象,一般有两种方法,一种是通过call_out()延时呼叫,另一种就是通过心跳。于是,对于要跨起离线前后的象做牢这类的事,大多都是采用condition。附:由于大多数MUD里的心跳是每两秒调一次,5+random是5至14次,因此可以看出每一个condition被调用的时间是平均19秒。然后它会按照condition的名字...

JRebel 6 破解版及使用方法

2.解压下载的jrebel6.0.0-crack.zip、jrebel6.0 jar包和破解文件。假设文件在D:/jrebel步骤:1中解压缩。eclipse下载jrebe插件,可以在市场上下载。2.打开eclipse的窗口首选项jrebel,打开优势选项卡,并将jar包的路径指向D:/jrebel/jrebel.jar。用CMD打开DOS窗口,输入cd/d...

汇编指令MOV

格式:MOVDST,SRC例如:MOVEAX,#050aH;将十六进制050a传送到通用寄存器eax中MOVDI,BXMOVES,AXMOVAX,DSMOVAL,23HMOV[2000H],02HMOV[2061H],BX...

mysql 视图

如果更新的值不在视图范围内,则不允许更新。如果创建视图时未使用withcheck选项,则MySQL在更新视图中的某些数据时不会执行有效性检查。对于上面的团队视图,MySQL将使用视图的公式来替换它,视图公式将合并到select中。也就是说,它最终被提交给MySQL来处理SQL语句。具体来说,MySQL首先获得视图执行结果,该结果形成中间结果,并临时存储在内存...

中兴iptv机顶盒破解教程图文:亲测中兴B760EV3、B860A、B860AV1.1完美安装应用!非ttl破解![转]

一直以来,人们都认为中兴的盒子只能通过ttl破解,但现在我们不需要那么麻烦了。使用此工具,前后破解不超过3分钟!理论上支持破解所有中兴IPTV机顶盒!...