Last active
May 18, 2018 01:54
-
-
Save yangl/07b47c41f1f606693b05 to your computer and use it in GitHub Desktop.
OkHttpClient请求简单封装,支持重试、超时配置
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- HttpClien配置 --> | |
<bean id="tsdbHttpClient" class="com.uxin.metrics.util.HttpClient"> | |
<property name="apiUrl" value="${tsdb.server.url}"/> | |
<property name="retry" value="true"/> | |
</bean> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.uxin.metrics.util; | |
import com.alibaba.fastjson.JSON; | |
import com.squareup.okhttp.*; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.InitializingBean; | |
import org.springframework.retry.RetryCallback; | |
import org.springframework.retry.RetryContext; | |
import org.springframework.retry.backoff.BackOffPolicy; | |
import org.springframework.retry.backoff.ExponentialRandomBackOffPolicy; | |
import org.springframework.retry.policy.SimpleRetryPolicy; | |
import org.springframework.retry.support.RetryTemplate; | |
import org.springframework.util.Assert; | |
import java.io.IOException; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* OkHttpClient请求简单封装,支持重试、超时配置 | |
* <p> | |
* 线程安全的 | |
* | |
* @author YAGNLiiN | |
* @date 2015-09-23 11:16 | |
*/ | |
public class HttpClient implements InitializingBean { | |
private static final Logger logger = LoggerFactory.getLogger(HttpClient.class); | |
// 超时时长 | |
private Long connectTimeout = 10L * 1000; | |
private Long readTimeout = 10L * 1000; | |
private Long writeTimeout = 10L * 1000; | |
// 是否重试 | |
private Boolean retry = true; | |
// 失败重试次数 | |
private Integer retryTimes = 2; | |
// 请求服务器地址 | |
private String apiUrl; | |
// 用OkHttpClient实现 | |
private OkHttpClient client; | |
// 重试 | |
private RetryTemplate retryTemplate; | |
// @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 2000)) | |
public <T> String postBody(String baseUri, T content) { | |
Assert.notNull(content, "请求内容不能为空"); | |
logger.info("*****发送HTTP POST[{}]请求,body类型为{}*****", baseUri, content.getClass()); | |
String rs = null; | |
String body = JSON.toJSONString(content); | |
RequestBody rb = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body); | |
final Request req = new Request.Builder().url(apiUrl + baseUri).post(rb).build(); | |
try { | |
retryTemplate.execute(new RetryCallback<String, IOException>() { | |
@Override | |
public String doWithRetry(RetryContext context) throws IOException { | |
// resp 关闭 | |
try (Response resp = client.newCall(req).execute()){ | |
if (resp.isSuccessful()) { | |
return resp.body().string(); | |
} else { | |
throw new IOException("Unexpected code " + resp); | |
} | |
} | |
} | |
}); | |
} catch (Throwable e) { | |
if (logger.isErrorEnabled()) { | |
logger.error("*****发送HTTP POST[{}]请求,body内容为{}*****", baseUri, body); | |
logger.error("*****发送HTTP POST[" + baseUri + "] 请求操失败,异常详情:*****", e); | |
} | |
} | |
return rs; | |
} | |
@Override | |
public void afterPropertiesSet() throws Exception { | |
// 设置OkHttpClient参数 | |
client = new OkHttpClient(); | |
client.setConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS); | |
client.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS); | |
client.setWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS); | |
// 重试策略 | |
retryTemplate = new RetryTemplate(); | |
SimpleRetryPolicy srp = new SimpleRetryPolicy(); | |
int maxAttempts = 1; | |
if (retry) { | |
maxAttempts = maxAttempts + retryTimes; | |
} | |
srp.setMaxAttempts(maxAttempts); | |
retryTemplate.setRetryPolicy(srp); | |
BackOffPolicy bo = new ExponentialRandomBackOffPolicy(); | |
retryTemplate.setBackOffPolicy(bo); | |
} | |
public Long getConnectTimeout() { | |
return connectTimeout; | |
} | |
public void setConnectTimeout(Long connectTimeout) { | |
this.connectTimeout = connectTimeout; | |
} | |
public Long getWriteTimeout() { | |
return writeTimeout; | |
} | |
public void setWriteTimeout(Long writeTimeout) { | |
this.writeTimeout = writeTimeout; | |
} | |
public Long getReadTimeout() { | |
return readTimeout; | |
} | |
public void setReadTimeout(Long readTimeout) { | |
this.readTimeout = readTimeout; | |
} | |
public Boolean getRetry() { | |
return retry; | |
} | |
public void setRetry(Boolean retry) { | |
this.retry = retry; | |
} | |
public Integer getRetryTimes() { | |
return retryTimes; | |
} | |
public void setRetryTimes(Integer retryTimes) { | |
this.retryTimes = retryTimes; | |
} | |
public String getApiUrl() { | |
return apiUrl; | |
} | |
public void setApiUrl(String apiUrl) { | |
this.apiUrl = apiUrl; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- httpclient --> | |
<dependency> | |
<groupId>com.squareup.okhttp</groupId> | |
<artifactId>okhttp</artifactId> | |
<version>2.5.0</version> | |
</dependency> | |
<dependency> | |
<groupId>org.springframework.retry</groupId> | |
<artifactId>spring-retry</artifactId> | |
<version>1.1.2.RELEASE</version> | |
</dependency> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment