In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to use ApacheHttpClient instead of the default client mode in SpringCloud Feign". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use ApacheHttpClient instead of the default client way in SpringCloud Feign".
Comparison of using ApacheHttpClient instead of default clientApacheHttpClient and default implementation
By default, Feign uses JDK's native URLConnection to send HTTP requests, and there is no connection pool, but a persistent connection is maintained for each address, that is, using HTTP's persistence connection.
ApacheHttpClient implements connection pooling, and it encapsulates request headers, parameters, contents, responses, etc., to access http, which makes it easy for clients to send HTTP requests.
ApacheHttpClient usage
Maven dependence
Org.springframework.cloud spring-cloud-starter-openfeign org.apache.httpcomponents httpclient 4.5.7 io.github.openfeign feign-httpclient 10.1.0
Modification of configuration file
Feign: httpclient: enabled: true
Create an ApacheHttpClient client
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;@Slf4jpublic 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; / * maxConnTotal is the largest number of connections in use at the same time * / this.maxConnTotal = maxConnTotal / * maxConnPerRoute is the maximum number of connections in use for a domain name at the same time * / 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 (); / / if the server has enabled TLS client authentication, you need to specify 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 () }} / / if https uses a self-signed certificate, you need to specify 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);}}
You can use builder directly to create an ApacheHttpClient when using it.
Apache's default retry mechanism for HttpClient maven org.apache.httpcomponents httpclient 4.5.2 abnormal retry log
2017-01-31 1919 askScheduler-13 31V 39.057 INFO 3873-[askScheduler-13] o.apache.http.impl.execchain.RetryExec: I 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 askScheduler-13 31V 39.058 INFO 3873-[askScheduler-13] o.apache.http.impl.execchain.RetryExec: Retrying request to {}-> http://192.168.99.100:8080
RetryExec
Org/apache/http/impl/execchain/RetryExec.java
/ * Request executor in the request execution chain that is responsible * for making a decision whether a request failed due to an I am O error * should be re-executed. *
* Further responsibilities such as communication with the opposite * endpoint is delegated to the next executor in the request execution * chain. *
* * @ since 4.3 * / @ Immutablepublic 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 exception 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;} DefaultHttpRequestRetryHandler
Org/apache/http/impl/client/DefaultHttpRequestRetryHandler.java
/ * * The default {@ link HttpRequestRetryHandler} used by request executors. * * @ since 4.0* / @ Immutablepublic class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler {public static final DefaultHttpRequestRetryHandler INSTANCE = new DefaultHttpRequestRetryHandler (); / * * the number of times a method will be retried * / private final int retryCount; / * * Whether or not methods that have successfully sent their request will be retried * / private final boolean requestSentRetryEnabled; private final Set
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 234
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.