spring boot封裝HttpClient

來源:互聯網
上載者:User

轉載於:https://blog.csdn.net/liuchuanhong1/article/details/68194036


最近使用到了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介面,代碼如下:

[java]  view plain  copy 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; &n

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.