Spring5的WebClient使用詳解

前言

Spring5帶來了新的響應式web開發框架WebFlux,同時,也引入了新的HttpClient框架WebClient。WebClient是Spring5中引入的執行 HTTP 請求的非阻塞、反應式客戶端。它對同步和異步以及流方案都有很好的支持,WebClient發佈後,RestTemplate將在未來版本中棄用,而且不會向前添加主要新功能。html

WebClient與RestTemplate比較

WebClient是一個功能完善的Http請求客戶端,與RestTemplate相比,WebClient支持如下內容:react

  • 非阻塞 I/O。
  • 反應流背壓(消費者消費負載太高時主動反饋生產者放慢生產速度的一種機制)。
  • 具備高併發性,硬件資源消耗更少。
  • 流暢的API設計。
  • 同步和異步交互。
  • 流式傳輸支持

HTTP底層庫選擇

Spring5的WebClient客戶端和WebFlux服務器都依賴於相同的非阻塞編解碼器來編碼和解碼請求和響應內容。默認底層使用Netty,內置支持Jetty反應性HttpClient實現。同時,也能夠經過編碼的方式實現ClientHttpConnector接口自定義新的底層庫;如切換Jetty實現:git

WebClient.builder()
                .clientConnector(new JettyClientHttpConnector())
                .build();

WebClient配置

基礎配置

WebClient實例構造器能夠設置一些基礎的全局的web請求配置信息,好比默認的cookie、header、baseUrl等github

WebClient.builder()
                .defaultCookie("kl","kl")
                .defaultUriVariables(ImmutableMap.of("name","kl"))
                .defaultHeader("header","kl")
                .defaultHeaders(httpHeaders -> {
                    httpHeaders.add("header1","kl");
                    httpHeaders.add("header2","kl");
                })
                .defaultCookies(cookie ->{
                    cookie.add("cookie1","kl");
                    cookie.add("cookie2","kl");
                })
                .baseUrl("http://www.kailing.pub")
                .build();

底層依賴Netty庫配置

經過定製Netty底層庫,能夠配置SSl安全鏈接,以及請求超時,讀寫超時等。這裏須要注意一個問題,默認的鏈接池最大鏈接500。獲取鏈接超時默認是45000ms,你能夠配置成動態的鏈接池,就能夠突破這些默認配置,也能夠根據業務本身制定。包括Netty的select線程和工做線程也均可以本身設置。web

//配置動態鏈接池
         //ConnectionProvider provider = ConnectionProvider.elastic("elastic pool");
         //配置固定大小鏈接池,如最大鏈接數、鏈接獲取超時、空閒鏈接死亡時間等
         ConnectionProvider provider = ConnectionProvider.fixed("fixed", 45, 4000, Duration.ofSeconds(6));
         HttpClient httpClient = HttpClient.create(provider)
                 .secure(sslContextSpec -> {
                     SslContextBuilder sslContextBuilder = SslContextBuilder.forClient()
                             .trustManager(new File("E://server.truststore"));
                     sslContextSpec.sslContext(sslContextBuilder);
                 }).tcpConfiguration(tcpClient -> {
                     //指定Netty的select 和 work線程數量
                     LoopResources loop = LoopResources.create("kl-event-loop", 1, 4, true);
                     return tcpClient.doOnConnected(connection -> {
                         //讀寫超時設置
                         connection.addHandlerLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS))
                                 .addHandlerLast(new WriteTimeoutHandler(10));
                     })
                             //鏈接超時設置
                             .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                             .option(ChannelOption.TCP_NODELAY, true)
                             .runOn(loop);
                 });
 
         WebClient.builder()
                 .clientConnector(new ReactorClientHttpConnector(httpClient))
                 .build();

關於鏈接池的設置,據羣友反饋,他們在使用WebClient是併發場景下會拋獲取鏈接異常。異常以下:編程

Caused by: reactor.netty.internal.shaded.reactor.pool.PoolAcquireTimeoutException: Pool#acquire(Duration) has been pending for more than the configured timeout of 45000ms

後經博主深刻研究發現,WebClient底層依賴庫reactory-netty在不一樣的版本下,初始化默認TcpTcpResources策略不同,博主在網關係統中使用的reactory-netty版本是0.8.3,默認建立的是動態的鏈接池,即便在併發場景下也沒發生過這種異常。而在0.9.x後,初始化的是固定大小的鏈接池,這位羣友正是由於使用的是0.9.1的reactory-netty,在併發時致使鏈接不可用,等待默認的45s後就拋異常了。因此,使用最新版本的WebClient必定要根據本身的業務場景結合博主上面的Netty HttpClient配置示例合理設置好底層資源。api

編解碼配置

針對特定的數據交互格式,能夠設置自定義編解碼的模式,以下:安全

ExchangeStrategies strategies = ExchangeStrategies.builder()
                .codecs(configurer -> {
                    configurer.customCodecs().decoder(new Jackson2JsonDecoder());
                    configurer.customCodecs().encoder(new Jackson2JsonEncoder());
                })
                .build();
        WebClient.builder()
                .exchangeStrategies(strategies)
                .build();

get請求示例

uri構造時支持屬性佔位符,真實參數在入參時排序好就能夠。同時能夠經過accept設置媒體類型,以及編碼。最終的結果值是經過Mono和Flux來接收的,在subscribe方法中訂閱返回值。服務器

WebClient client = WebClient.create("http://www.kailing.pub");
        Mono<String> result = client.get()
                .uri("/article/index/arcid/{id}.html", 256)
                .acceptCharset(StandardCharsets.UTF_8)
                .accept(MediaType.TEXT_HTML)
                .retrieve()
                .bodyToMono(String.class);
        result.subscribe(System.err::println);

若是須要攜帶複雜的查詢參數,能夠經過UriComponentsBuilder構造出uri請求地址,如:websocket

//定義query參數
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("name", "kl");
        params.add("age", "19");
        //定義url參數
        Map<String, Object> uriVariables = new HashMap<>();
        uriVariables.put("id", 200);
        String uri = UriComponentsBuilder.fromUriString("/article/index/arcid/{id}.html")
                .queryParams(params)
                .uriVariables(uriVariables)
                .toUriString();

下載文件時,由於不清楚各類格式文件對應的MIME Type,能夠設置accept爲MediaType.ALL,而後使用Spring的Resource來接收數據便可,如:

WebClient.create("https://kk-open-public.oss-cn-shanghai.aliyuncs.com/xxx.xlsx")
                .get()
                .accept(MediaType.ALL)
                .retrieve()
                .bodyToMono(Resource.class)
                .subscribe(resource -> {
                    try {
                        File file = new File("E://abcd.xlsx");
                        FileCopyUtils.copy(StreamUtils.copyToByteArray(resource.getInputStream()), file);
                    }catch (IOException ex){}
                });

post請求示例

post請求示例演示了一個比較複雜的場景,同時包含表單參數和文件流數據。若是是普通post請求,直接經過bodyValue設置對象實例便可。不用FormInserter構造。

WebClient client = WebClient.create("http://www.kailing.pub");
        FormInserter formInserter = fromMultipartData("name","kl")
                .with("age",19)
                .with("map",ImmutableMap.of("xx","xx"))
                .with("file",new File("E://xxx.doc"));
        Mono<String> result = client.post()
                .uri("/article/index/arcid/{id}.html", 256)
                .contentType(MediaType.APPLICATION_JSON)
                .body(formInserter)
                //.bodyValue(ImmutableMap.of("name","kl"))
                .retrieve()
                .bodyToMono(String.class);
        result.subscribe(System.err::println);

同步返回結果

上面演示的都是異步的經過mono的subscribe訂閱響應值。固然,若是你想同步阻塞獲取結果,也能夠經過.block()阻塞當前線程獲取返回值。

WebClient client =  WebClient.create("http://www.kailing.pub");
      String result = client .get()
                .uri("/article/index/arcid/{id}.html", 256)
                .retrieve()
                .bodyToMono(String.class)
                .block();
        System.err.println(result);

可是,若是須要進行多個調用,則更高效地方式是避免單獨阻塞每一個響應,而是等待組合結果,如:

WebClient client =  WebClient.create("http://www.kailing.pub");
        Mono<String> result1Mono = client .get()
                .uri("/article/index/arcid/{id}.html", 255)
                .retrieve()
                .bodyToMono(String.class);
        Mono<String> result2Mono = client .get()
                .uri("/article/index/arcid/{id}.html", 254)
                .retrieve()
                .bodyToMono(String.class);
        Map<String,String>  map = Mono.zip(result1Mono, result2Mono, (result1, result2) -> {
            Map<String, String> arrayList = new HashMap<>();
            arrayList.put("result1", result1);
            arrayList.put("result2", result2);
            return arrayList;
        }).block();
        System.err.println(map.toString());

Filter過濾器

能夠經過設置filter攔截器,統一修改攔截請求,好比認證的場景,以下示例,filter註冊單個攔截器,filters能夠註冊多個攔截器,basicAuthentication是系統內置的用於basicAuth的攔截器,limitResponseSize是系統內置用於限制響值byte大小的攔截器

WebClient.builder()
                .baseUrl("http://www.kailing.pub")
                .filter((request, next) -> {
                    ClientRequest filtered = ClientRequest.from(request)
                            .header("foo", "bar")
                            .build();
                    return next.exchange(filtered);
                })
                .filters(filters ->{
                    filters.add(ExchangeFilterFunctions.basicAuthentication("username","password"));
                    filters.add(ExchangeFilterFunctions.limitResponseSize(800));
                })
                .build().get()
                .uri("/article/index/arcid/{id}.html", 254)
                .retrieve()
                .bodyToMono(String.class)
                .subscribe(System.err::println);

websocket支持

WebClient不支持websocket請求,請求websocket接口時須要使用WebSocketClient,如:

WebSocketClient client = new ReactorNettyWebSocketClient();
URI url = new URI("ws://localhost:8080/path");
client.execute(url, session ->
        session.receive()
                .doOnNext(System.out::println)
                .then());

結語

咱們已經在業務api網關、短信平臺等多個項目中使用WebClient,從網關的流量和穩定足以可見WebClient的性能和穩定性。響應式編程模型是將來的web編程趨勢,RestTemplate會逐步被取締淘汰,而且官方已經不在更新和維護。WebClient很好的支持了響應式模型,並且api設計友好,是博主力薦新的HttpClient庫。趕忙試試吧。

相關文章
相關標籤/搜索