您好,登錄后才能下訂單哦!
本篇文章為大家展示了Spring5中如何使用WebClient,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
WebClient是一個(gè)功能完善的Http請求客戶端,與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ì)。
同步和異步交互。
流式傳輸支持
Spring5的WebClient客戶端和WebFlux服務(wù)器都依賴于相同的非阻塞編解碼器來編碼和解碼請求和響應(yīng)內(nèi)容。默認(rèn)底層使用Netty,內(nèi)置支持Jetty反應(yīng)性HttpClient實(shí)現(xiàn)。同時(shí),也可以通過編碼的方式實(shí)現(xiàn)ClientHttpConnector接口自定義新的底層庫;如切換Jetty實(shí)現(xiàn):
WebClient.builder() .clientConnector(new JettyClientHttpConnector()) .build();
WebClient實(shí)例構(gòu)造器可以設(shè)置一些基礎(chǔ)的全局的web請求配置信息,比如默認(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底層庫,可以配置SSl安全連接,以及請求超時(shí),讀寫超時(shí)等。這里需要注意一個(gè)問題,默認(rèn)的連接池最大連接500。獲取連接超時(shí)默認(rèn)是45000ms,你可以配置成動(dòng)態(tài)的連接池,就可以突破這些默認(rèn)配置,也可以根據(jù)業(yè)務(wù)自己制定。包括Netty的select線程和工作線程也都可以自己設(shè)置。
//配置動(dòng)態(tài)連接池 //ConnectionProvider provider = ConnectionProvider.elastic("elastic pool"); //配置固定大小連接池,如最大連接數(shù)、連接獲取超時(shí)、空閑連接死亡時(shí)間等 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線程數(shù)量 LoopResources loop = LoopResources.create("kl-event-loop", 1, 4, true); return tcpClient.doOnConnected(connection -> { //讀寫超時(shí)設(shè)置 connection.addHandlerLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS)) .addHandlerLast(new WriteTimeoutHandler(10)); }) //連接超時(shí)設(shè)置 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.TCP_NODELAY, true) .runOn(loop); }); WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build();
關(guān)于連接池的設(shè)置,據(jù)群友反饋,他們在使用WebClient是并發(fā)場景下會(huì)拋獲取連接異常。異常如下:
Caused by: reactor.netty.internal.shaded.reactor.pool.PoolAcquireTimeoutException: Pool#acquire(Duration) has been pending for more than the configured timeout of 45000ms
后經(jīng)博主深入研究發(fā)現(xiàn),WebClient底層依賴庫reactory-netty在不同的版本下,初始化默認(rèn)TcpTcpResources策略不一樣,博主在網(wǎng)關(guān)系統(tǒng)中使用的reactory-netty版本是0.8.3,默認(rèn)創(chuàng)建的是動(dòng)態(tài)的連接池,即使在并發(fā)場景下也沒發(fā)生過這種異常。而在0.9.x后,初始化的是固定大小的連接池,這位群友正是因?yàn)槭褂玫氖?.9.1的reactory-netty,在并發(fā)時(shí)導(dǎo)致連接不可用,等待默認(rèn)的45s后就拋異常了。所以,使用最新版本的WebClient一定要根據(jù)自己的業(yè)務(wù)場景結(jié)合博主上面的Netty HttpClient配置示例合理設(shè)置好底層資源。
默認(rèn)策略改動(dòng)的初衷是有人在github提出了默認(rèn)使用動(dòng)態(tài)連接池的顧慮:https://github.com/reactor/reactor-netty/issues/578
最終代碼調(diào)整的的pull記錄:https://github.com/reactor/reactor-netty/pull/812
reactory-netty-0.8.x初始化TcpTcpResources
reactory-netty-0.9.x初始化TcpTcpResources
針對特定的數(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();
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) .acceptCharset(StandardCharsets.UTF_8) .accept(MediaType.TEXT_HTML) .retrieve() .bodyToMono(String.class); result.subscribe(System.err::println);
如果需要攜帶復(fù)雜的查詢參數(shù),可以通過UriComponentsBuilder構(gòu)造出uri請求地址,如:
//定義query參數(shù) MultiValueMapparams = new LinkedMultiValueMap<>(); params.add("name", "kl"); params.add("age", "19"); //定義url參數(shù) MapuriVariables = new HashMap<>(); uriVariables.put("id", 200); String uri = UriComponentsBuilder.fromUriString("/article/index/arcid/{id}.html") .queryParams(params) .uriVariables(uriVariables)
下載文件時(shí),因?yàn)椴磺宄鞣N格式文件對應(yīng)的MIME Type,可以設(shè)置accept為MediaType.ALL,然后使用Spring的Resource來接收數(shù)據(jù)即可,如:
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請求示例演示了一個(gè)比較復(fù)雜的場景,同時(shí)包含表單參數(shù)和文件流數(shù)據(jù)。如果是普通post請求,直接通過bodyValue設(shè)置對象實(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);
上面演示的都是異步的通過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); Mapmap = Mono.zip(result1Mono, result2Mono, (result1, result2) -> { MaparrayList = new HashMap<>(); arrayList.put("result1", result1); arrayList.put("result2", result2); return arrayList; }).block(); System.err.println(map.toString());
可以通過設(shè)置filter攔截器,統(tǒng)一修改攔截請求,比如認(rèn)證的場景,如下示例,filter注冊單個(gè)攔截器,filters可以注冊多個(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);
WebClient不支持websocket請求,請求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());
上述內(nèi)容就是Spring5中如何使用WebClient,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。