spring boot封装封装HttpClient的示例代码的示例代码
主要介绍了spring boot封装HttpClient的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一起跟随小编过来看看吧
最近使用到了HttpClient,看了一下官方文档:HttpClient implementations are expected to be thread safe. It is recommended
that the same instance of this class is reused for multiple request executions,翻译过来的意思就是:HttpClient的实现是线
程安全的,可以重用相同的实例来执行多次请求。遇到这种描述的话,我们就应该想到,需要对HttpClient来进行封装了。由
于是使用的spring boot,所以下面来结合spring boot来封装HttpClient。
一、一、Request retry handler(请求重试处理请求重试处理)
为了使自定义异常机制生效,需要实现HttpRequestRetryHandler接口,代码如下:
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.protocol.HttpContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 描述:HttpClient的重试处理机制
*/
@Configuration
public class MyhttpRequestRetryHandler {
@Value("${httpclient.config.retryTime}")// 此处建议采用@ConfigurationProperties(prefix="httpclient.config")方式,方便复用
private int retryTime;
@Bean
public HttpRequestRetryHandler httpRequestRetryHandler() {
// 请求重试
final int retryTime = this.retryTime;
return new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
// Do not retry if over max retry count,如果重试次数超过了retryTime,则不再重试请求
if (executionCount >= retryTime) {
return false;
}
// 服务端断掉客户端的连接异常
if (exception instanceof NoHttpResponseException) {
return true;
}
// time out 超时重试
if (exception instanceof InterruptedIOException) {
return true;
}
// Unknown host
if (exception instanceof UnknownHostException) {
return false;
}
// Connection refused
if (exception instanceof ConnectTimeoutException) {
return false;
}
// SSL handshake exception
if (exception instanceof SSLException) {
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
if (!(request instanceof HttpEntityEnclosingRequest)) {
return true;
}
return false;
}
};
}
评论1
最新资源