Python 官方文档:入门教程 => 点击学习
目录使用ApacheHttpClient代替默认clientApacheHttpClient和默认实现的比较ApacheHttpClient使用apache的HttpClient默认
maven 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
</dependency>
<dependency>
<groupId>io.GitHub.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>10.1.0</version>
</dependency>
配置文件的修改
feign:
httpclient:
enabled: true
创建ApacheHttpClient客户端
import javax.net.ssl.SSLContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.springframework.util.ResourceUtils;
import feign.httpclient.ApacheHttpClient;
@Slf4j
public class FeignClientBuilder {
private boolean enabled;
private String keyPassWord;
private String keyStore;
private String keyStorePassword;
private String trustStore;
private String trustStorePassword;
private int maxConnTotal = 2048;
private int maxConnPerRoute = 512;
public FeignClientBuilder(boolean enabled, String keyPassword, String keyStore, String keyStorePassword, String trustStore, String trustStorePassword, int maxConnTotal, int maxConnPerRoute) {
this.enabled = enabled;
this.keyPassword = keyPassword;
this.keyStore = keyStore;
this.keyStorePassword = keyStorePassword;
this.trustStore = trustStore;
this.trustStorePassword = trustStorePassword;
this.maxConnTotal = maxConnTotal;
this.maxConnPerRoute = maxConnPerRoute;
}
public ApacheHttpClient apacheHttpClient() {
CloseableHttpClient defaultHttpClient = HttpClients.custom()
.setMaxConnTotal(maxConnTotal)
.setMaxConnPerRoute(maxConnPerRoute)
.build();
ApacheHttpClient defaultApacheHttpClient = new ApacheHttpClient(defaultHttpClient);
if (!enabled) {
return defaultApacheHttpClient;
}
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
// 如果 服务端启用了 TLS 客户端验证,则需要指定 keyStore
if (keyStore == null || keyStore.isEmpty()) {
return new ApacheHttpClient();
} else {
try {
sslContextBuilder
.loadKeyMaterial(
ResourceUtils.getFile(keyStore),
keyStorePassword.toCharArray(),
keyPassword.toCharArray());
} catch (Exception e) {
e.printStackTrace();
}
}
// 如果 https 使用自签名证书,则需要指定 trustStore
if (trustStore == null || trustStore.isEmpty()) {
} else {
try {
sslContextBuilder
// .loadTrustMaterial(TrustAllStrategy.INSTANCE)
.loadTrustMaterial(
ResourceUtils.getFile(trustStore),
trustStorePassword.toCharArray()
);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
SSLContext sslContext = sslContextBuilder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom()
.setMaxConnTotal(maxConnTotal)
.setMaxConnPerRoute(maxConnPerRoute)
.setSSLSocketFactory(sslsf)
.build();
ApacheHttpClient apacheHttpClient = new ApacheHttpClient(httpClient);
log.info("feign Client load with ssl.");
return apacheHttpClient;
} catch (Exception e) {
e.printStackTrace();
}
return defaultApacheHttpClient;
}
public static FeignClientBuilderBuilder builder() {
return new FeignClientBuilderBuilder();
}
public static class FeignClientBuilderBuilder {
private boolean enabled;
private String keyPassword;
private String keyStore;
private String keyStorePassword;
private String trustStore;
private String trustStorePassword;
private int maxConnTotal = 2048;
private int maxConnPerRoute = 512;
public FeignClientBuilderBuilder enabled(boolean enabled) {
this.enabled = enabled;
return this;
}
public FeignClientBuilderBuilder keyPassword(String keyPassword) {
this.keyPassword = keyPassword;
return this;
}
public FeignClientBuilderBuilder keyStore(String keyStore) {
this.keyStore = keyStore;
return this;
}
public FeignClientBuilderBuilder keyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
return this;
}
public FeignClientBuilderBuilder trustStore(String trustStore) {
this.trustStore = trustStore;
return this;
}
public FeignClientBuilderBuilder trustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
return this;
}
public FeignClientBuilderBuilder maxConnTotal(int maxConnTotal) {
this.maxConnTotal = maxConnTotal;
return this;
}
public FeignClientBuilderBuilder maxConnPerRoute(int maxConnPerRoute) {
this.maxConnPerRoute = maxConnPerRoute;
return this;
}
public FeignClientBuilder build() {
return new FeignClientBuilder(
this.enabled,
this.keyPassword,
this.keyStore,
this.keyStorePassword,
this.trustStore,
this.trustStorePassword,
this.maxConnTotal,
this.maxConnPerRoute
);
}
}
}
使用时可以直接使用builder来创建ApacheHttpClient。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
2017-01-31 19:31:39.057 INFO 3873 --- [askScheduler-13] o.apache.http.impl.execchain.RetryExec : I/O exception (org.apache.http.NoHttpResponseException) caught when processing request to {}->http://192.168.99.100:8080: The target server failed to respond
2017-01-31 19:31:39.058 INFO 3873 --- [askScheduler-13] o.apache.http.impl.execchain.RetryExec : Retrying request to {}->http://192.168.99.100:8080
org/apache/http/impl/execchain/RetryExec.java
@Immutable
public class RetryExec implements ClientExecChain {
private final Log log = LogFactory.getLog(getClass());
private final ClientExecChain requestExecutor;
private final HttpRequestRetryHandler retryHandler;
public RetryExec(
final ClientExecChain requestExecutor,
final HttpRequestRetryHandler retryHandler) {
Args.notNull(requestExecutor, "HTTP request executor");
Args.notNull(retryHandler, "HTTP request retry handler");
this.requestExecutor = requestExecutor;
this.retryHandler = retryHandler;
}
@Override
public CloseableHttpResponse execute(
final HttpRoute route,
final HttpRequestWrapper request,
final HttpClientContext context,
final HttpExecutionAware execAware) throws IOException, HttpException {
Args.notNull(route, "HTTP route");
Args.notNull(request, "HTTP request");
Args.notNull(context, "HTTP context");
final Header[] origheaders = request.getAllHeaders();
for (int execCount = 1;; execCount++) {
try {
return this.requestExecutor.execute(route, request, context, execAware);
} catch (final IOException ex) {
if (execAware != null && execAware.isAborted()) {
this.log.debug("Request has been aborted");
throw ex;
}
if (retryHandler.retryRequest(ex, execCount, context)) {
if (this.log.isInfoEnabled()) {
this.log.info("I/O exception ("+ ex.getClass().getName() +
") caught when processing request to "
+ route +
": "
+ ex.getMessage());
}
if (this.log.isDebugEnabled()) {
this.log.debug(ex.getMessage(), ex);
}
if (!RequestEntityProxy.isRepeatable(request)) {
this.log.debug("Cannot retry non-repeatable request");
throw new NonRepeatableRequestException("Cannot retry request " +
"with a non-repeatable request entity", ex);
}
request.setHeaders(origheaders);
if (this.log.isInfoEnabled()) {
this.log.info("Retrying request to " + route);
}
} else {
if (ex instanceof NoHttpResponseException) {
final NoHttpResponseException updatedex = new NoHttpResponseException(
route.getTargetHost().toHostString() + " failed to respond");
updatedex.setStackTrace(ex.getStackTrace());
throw updatedex;
} else {
throw ex;
}
}
}
}
}
}
org/apache/http/impl/client/DefaultHttpRequestRetryHandler.java
@Immutable
public class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler {
public static final DefaultHttpRequestRetryHandler INSTANCE = new DefaultHttpRequestRetryHandler();
private final int retryCount;
private final boolean requestSentRetryEnabled;
private final Set<Class<? extends IOException>> nonRetriableClasses;
protected DefaultHttpRequestRetryHandler(
final int retryCount,
final boolean requestSentRetryEnabled,
final Collection<Class<? extends IOException>> clazzes) {
super();
this.retryCount = retryCount;
this.requestSentRetryEnabled = requestSentRetryEnabled;
this.nonRetriableClasses = new HashSet<Class<? extends IOException>>();
for (final Class<? extends IOException> clazz: clazzes) {
this.nonRetriableClasses.add(clazz);
}
}
@SuppressWarnings("unchecked")
public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) {
this(retryCount, requestSentRetryEnabled, Arrays.asList(
InterruptedIOException.class,
UnknownHostException.class,
ConnectException.class,
SSLException.class));
}
public DefaultHttpRequestRetryHandler() {
this(3, false);
}
@Override
public boolean retryRequest(
final IOException exception,
final int executionCount,
final HttpContext context) {
Args.notNull(exception, "Exception parameter");
Args.notNull(context, "HTTP context");
if (executionCount > this.retryCount) {
// Do not retry if over max retry count
return false;
}
if (this.nonRetriableClasses.contains(exception.getClass())) {
return false;
} else {
for (final Class<? extends IOException> rejectException : this.nonRetriableClasses) {
if (rejectException.isInstance(exception)) {
return false;
}
}
}
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final HttpRequest request = clientContext.getRequest();
if(requestIsAborted(request)){
return false;
}
if (handleAsIdempotent(request)) {
// Retry if the request is considered idempotent
return true;
}
if (!clientContext.isRequestSent() || this.requestSentRetryEnabled) {
// Retry if the request has not been sent fully or
// if it's OK to retry methods that have been sent
return true;
}
// otherwise do not retry
return false;
}
public boolean isRequestSentRetryEnabled() {
return requestSentRetryEnabled;
}
public int getRetryCount() {
return retryCount;
}
protected boolean handleAsIdempotent(final HttpRequest request) {
return !(request instanceof HttpEntityEnclosingRequest);
}
@Deprecated
protected boolean requestIsAborted(final HttpRequest request) {
HttpRequest req = request;
if (request instanceof RequestWrapper) { // does not forward request to original
req = ((RequestWrapper) request).getOriginal();
}
return (req instanceof HttpUriRequest && ((HttpUriRequest)req).isAborted());
}
}
默认重试3次,三次都失败则抛出NoHttpResponseException或其他异常
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: SpringCloud Feign使用ApacheHttpClient代替默认client方式
本文链接: https://lsjlt.com/news/141821.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0