RestTemplate + okhttp3 簡單使用

RestTemplate:
是 Spring 提供的用于訪問Rest服務(wù)的客戶端, RestTemplate 提供了多種便捷訪問遠(yuǎn)程Http服務(wù)的方法,能夠大大提高客戶端的編寫效率。
–注意RestTemplate只有初始化配置(也可以不配,有默認(rèn)的),沒有什么連接池
okhttp3:官方文檔
OkHttp是一個高效的HTTP客戶端:

  • ? HTTP / 2支持允許對同一主機的所有請求共享一個套接字。
  • ? 連接池可減少請求延遲(如果HTTP / 2不可用)。
  • ?透明的GZIP縮小了下載大小。
  • ?響應(yīng)緩存可以完全避免網(wǎng)絡(luò)重復(fù)請求。

    當(dāng)網(wǎng)絡(luò)出現(xiàn)問題時,OkHttp會堅持不懈:它將從常見的連接問題中靜默恢復(fù)。如果您的服務(wù)具有多個IP地址,則在第一次連接失敗時,OkHttp將嘗試使用備用地址。這對于IPv4 + IPv6和冗余數(shù)據(jù)中心中托管的服務(wù)是必需的。OkHttp支持現(xiàn)代TLS功能(TLS 1.3,ALPN,證書固定)??梢詫⑵渑渲脼榛赝艘垣@得廣泛的連接性。
    使用OkHttp很容易。它的請求/響應(yīng)API具有流暢的構(gòu)建器和不變性。它支持同步阻塞調(diào)用和帶有回調(diào)的異步調(diào)用。

1.添加pom依賴

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>

2.application.properties設(shè)置相關(guān)配置參數(shù)

ok.http.connect-timeout=1
ok.http.read-timeout=3
ok.http.write-timeout=3
# 連接池中整體的空閑連接的最大數(shù)量
ok.http.max-idle-connections=200
# 連接空閑時間最多為 300 秒
ok.http.keep-alive-duration=300

2.RestTemplateConfig配置類

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Configuration
public class RestTemplateConfig {

    @Value("${ok.http.connect-timeout}")
    private Integer connectTimeout;

    @Value("${ok.http.read-timeout}")
    private Integer readTimeout;

    @Value("${ok.http.write-timeout}")
    private Integer writeTimeout;

    @Value("${ok.http.max-idle-connections}")
    private Integer maxIdleConnections;

    @Value("${ok.http.keep-alive-duration}")
    private Long keepAliveDuration;


    /**
     * 聲明 RestTemplate
     */
    @Bean
    public RestTemplate httpRestTemplate() {
        ClientHttpRequestFactory factory = httpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(factory);
        // 可以添加消息轉(zhuǎn)換
        //restTemplate.setMessageConverters(...);
        // 可以增加攔截器
        //restTemplate.setInterceptors(...);
        return restTemplate;
    }

    public ClientHttpRequestFactory httpRequestFactory() {
        return new OkHttp3ClientHttpRequestFactory(okHttpConfigClient());
    }

    public OkHttpClient okHttpConfigClient(){
         return new OkHttpClient().newBuilder()
                 .connectionPool(pool())
                 .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                 .readTimeout(readTimeout, TimeUnit.SECONDS)
                 .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                 .hostnameVerifier((hostname, session) -> true)
                 // 設(shè)置代理
//              .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)))
                 // 攔截器
//                .addInterceptor()
                 .build();
    }

    public ConnectionPool pool() {
        return new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
    }

}

3.測試controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RestTemplateController {
    @Autowired
    private RestTemplate httpRestTemplate;


    @GetMapping("testRestTemplate")
    public ResponseEntity testRestTemplate(){
        ResponseEntity responseEntity = httpRestTemplate.getForEntity("http://localhost:8080/testReturn", String.class);
        System.out.println(responseEntity);
        return responseEntity;
    }

    @GetMapping("testReturn")
    public String testReturn() throws InterruptedException {
        Thread.sleep(1000);
        return "test";
    }

}

相關(guān)文章鏈接:

http://www.itdecent.cn/p/1f1d48fd2208

https://blog.csdn.net/hd20086996/article/details/105282035

https://blog.csdn.net/u010979642/article/details/89103162

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容