Spring5中的WebClient使用方法詳解
前言
Spring5帶來了新的響應(yīng)式web開發(fā)框架WebFlux,同時(shí),也引入了新的HttpClient框架WebClient。WebClient是Spring5中引入的執(zhí)行 HTTP 請(qǐng)求的非阻塞、反應(yīng)式客戶端。它對(duì)同步和異步以及流方案都有很好的支持,WebClient發(fā)布后,RestTemplate將在將來版本中棄用,并且不會(huì)向前添加主要新功能。
WebClient與RestTemplate比較
WebClient是一個(gè)功能完善的Http請(qǐng)求客戶端,與RestTemplate相比,WebClient支持以下內(nèi)容:
- 非阻塞 I/O。
- 反應(yīng)流背壓(消費(fèi)者消費(fèi)負(fù)載過高時(shí)主動(dòng)反饋生產(chǎn)者放慢生產(chǎn)速度的一種機(jī)制)。
- 具有高并發(fā)性,硬件資源消耗更少。
- 流暢的API設(shè)計(jì)。
- 同步和異步交互。
- 流式傳輸支持
HTTP底層庫(kù)選擇
Spring5的WebClient客戶端和WebFlux服務(wù)器都依賴于相同的非阻塞編解碼器來編碼和解碼請(qǐng)求和響應(yīng)內(nèi)容。默認(rèn)底層使用Netty,內(nèi)置支持Jetty反應(yīng)性HttpClient實(shí)現(xiàn)。同時(shí),也可以通過編碼的方式實(shí)現(xiàn)ClientHttpConnector接口自定義新的底層庫(kù);如切換Jetty實(shí)現(xiàn):
WebClient.builder() .clientConnector(new JettyClientHttpConnector()) .build();
WebClient配置
基礎(chǔ)配置
WebClient實(shí)例構(gòu)造器可以設(shè)置一些基礎(chǔ)的全局的web請(qǐng)求配置信息,比如默認(rèn)的cookie、header、baseUrl等
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庫(kù)配置
通過定制Netty底層庫(kù),可以配置SSl安全連接,以及請(qǐng)求超時(shí),讀寫超時(shí)等
HttpClient httpClient = HttpClient.create() .secure(sslContextSpec -> { SslContextBuilder sslContextBuilder = SslContextBuilder.forClient() .trustManager(new File("E://server.truststore")); sslContextSpec.sslContext(sslContextBuilder); }).tcpConfiguration(tcpClient -> { tcpClient.doOnConnected(connection -> //讀寫超時(shí)設(shè)置 connection.addHandlerLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS)) .addHandlerLast(new WriteTimeoutHandler(10)) ); //連接超時(shí)設(shè)置 tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.TCP_NODELAY,true); return tcpClient; }); WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build();
編解碼配置
針對(duì)特定的數(shù)據(jù)交互格式,可以設(shè)置自定義編解碼的模式,如下:
ExchangeStrategies strategies = ExchangeStrategies.builder() .codecs(configurer -> { configurer.customCodecs().decoder(new Jackson2JsonDecoder()); configurer.customCodecs().encoder(new Jackson2JsonEncoder()); }) .build(); WebClient.builder() .exchangeStrategies(strategies) .build();
get請(qǐng)求示例
uri構(gòu)造時(shí)支持屬性占位符,真實(shí)參數(shù)在入?yún)r(shí)排序好就可以。同時(shí)可以通過accept設(shè)置媒體類型,以及編碼。最終的結(jié)果值是通過Mono和Flux來接收的,在subscribe方法中訂閱返回值。
WebClient client = WebClient.create("http://www.kailing.pub"); Mono<String> result = client.get() .uri("/article/index/arcid/{id}.html", 256) .attributes(attr -> { attr.put("name", "kl"); attr.put("age", "28"); }) .acceptCharset(StandardCharsets.UTF_8) .accept(MediaType.TEXT_HTML) .retrieve() .bodyToMono(String.class); result.subscribe(System.err::println);
post請(qǐng)求示例
post請(qǐng)求示例演示了一個(gè)比較復(fù)雜的場(chǎng)景,同時(shí)包含表單參數(shù)和文件流數(shù)據(jù)。如果是普通post請(qǐng)求,直接通過bodyValue設(shè)置對(duì)象實(shí)例即可。不用FormInserter構(gòu)造。
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);
同步返回結(jié)果
上面演示的都是異步的通過mono的subscribe訂閱響應(yīng)值。當(dāng)然,如果你想同步阻塞獲取結(jié)果,也可以通過.block()阻塞當(dāng)前線程獲取返回值。
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);
但是,如果需要進(jìn)行多個(gè)調(diào)用,則更高效地方式是避免單獨(dú)阻塞每個(gè)響應(yīng),而是等待組合結(jié)果,如:
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過濾器
可以通過設(shè)置filter攔截器,統(tǒng)一修改攔截請(qǐng)求,比如認(rèn)證的場(chǎng)景,如下示例,filter注冊(cè)單個(gè)攔截器,filters可以注冊(cè)多個(gè)攔截器,basicAuthentication是系統(tǒng)內(nèi)置的用于basicAuth的攔截器,limitResponseSize是系統(tǒng)內(nèi)置用于限制響值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請(qǐng)求,請(qǐng)求websocket接口時(shí)需要使用WebSocketClient,如:
WebSocketClient client = new ReactorNettyWebSocketClient(); URI url = new URI("ws://localhost:8080/path"); client.execute(url, session -> session.receive() .doOnNext(System.out::println) .then());
結(jié)語(yǔ)
我們已經(jīng)在業(yè)務(wù)api網(wǎng)關(guān)、短信平臺(tái)等多個(gè)項(xiàng)目中使用WebClient,從網(wǎng)關(guān)的流量和穩(wěn)定足以可見WebClient的性能和穩(wěn)定性。響應(yīng)式編程模型是未來的web編程趨勢(shì),RestTemplate會(huì)逐步被取締淘汰,并且官方已經(jīng)不在更新和維護(hù)。WebClient很好的支持了響應(yīng)式模型,而且api設(shè)計(jì)友好,是博主力薦新的HttpClient庫(kù)。趕緊試試吧。
好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
云計(jì)算實(shí)驗(yàn):Java?MapReduce編程
這篇文章主要介紹了云計(jì)算實(shí)驗(yàn):Java?MapReduce編程,?居于Java圍繞MapReduce編程展開詳細(xì)內(nèi)容,文章助大家掌握MapReduce編程,理解MapReduce原理,需要的朋友可以參考一下2021-12-12springboot?vue測(cè)試平臺(tái)接口定義及發(fā)送請(qǐng)求功能實(shí)現(xiàn)
這篇文章主要為大家介紹了springboot+vue測(cè)試平臺(tái)接口定義及發(fā)送請(qǐng)求功能實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05dubbo集成zipkin獲取Traceid的實(shí)現(xiàn)
這篇文章主要介紹了dubbo集成zipkin獲取Traceid的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Kotlin + Retrofit + RxJava簡(jiǎn)單封裝使用詳解
這篇文章主要介紹了Kotlin + Retrofit + RxJava簡(jiǎn)單封裝使用詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07