本篇內容主要講解“Spring5怎么配置WebClient”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Spring5怎么配置WebClient”吧!
非阻塞 I/O。
反應流背壓(消費者消費負載過高時主動反饋生產者放慢生產速度的一種機制)。
具有高并發性,硬件資源消耗更少。
流暢的API設計。
同步和異步交互。
流式傳輸支持
HTTP底層庫選擇
Spring5的WebClient客戶端和WebFlux服務器都依賴于相同的非阻塞編解碼器來編碼和解碼請求和響應內容。默認底層使用Netty,內置支持Jetty反應性HttpClient實現。同時,也可以通過編碼的方式實現ClientHttpConnector接口自定義新的底層庫;如切換Jetty實現:
WebClient.builder() .clientConnector(new JettyClientHttpConnector()) .build();
基礎配置
WebClient實例構造器可以設置一些基礎的全局的web請求配置信息,比如默認的cookie、header、baseUrl等
WebClient.builder()
.defaultCookie("test","t1")
.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安全連接,以及請求超時,讀寫超時等。這里需要注意一個問題,默認的連接池最大連接500。獲取連接超時默認是45000ms,你可以配置成動態的連接池,就可以突破這些默認配置,也可以根據業務自己制定。包括Netty的select線程和工作線程也都可以自己設置。
//配置動態連接池
//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();針對特定的數據交互格式,可以設置自定義編解碼的模式,如下:
ExchangeStrategies strategies = ExchangeStrategies.builder()
.codecs(configurer -> {
configurer.customCodecs().decoder(new Jackson2JsonDecoder());
configurer.customCodecs().encoder(new Jackson2JsonEncoder());
})
.build();
WebClient.builder()
.exchangeStrategies(strategies)
.build();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請求地址,如:
//定義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")下載文件時,因為不清楚各種格式文件對應的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請求,直接通過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注冊單個攔截器,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);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()
);到此,相信大家對“Spring5怎么配置WebClient”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。