Spring5中WebClient怎么用-創(chuàng)新互聯(lián)

這篇文章將為大家詳細(xì)講解有關(guān)Spring5中WebClient怎么用,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

專業(yè)從事網(wǎng)站設(shè)計制作、成都網(wǎng)站建設(shè),高端網(wǎng)站制作設(shè)計,重慶小程序開發(fā),網(wǎng)站推廣的成都做網(wǎng)站的公司。優(yōu)秀技術(shù)團(tuán)隊竭力真誠服務(wù),采用HTML5+CSS3前端渲染技術(shù),成都響應(yīng)式網(wǎng)站建設(shè)公司,讓網(wǎng)站在手機(jī)、平板、PC、微信下都能呈現(xiàn)。建站過程建立專項小組,與您實時在線互動,隨時提供解決方案,暢聊想法和感受。

前言

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

WebClient與RestTemplate比較

WebClient是一個功能完善的Http請求客戶端,與RestTemplate相比,WebClient支持以下內(nèi)容:

非阻塞 I/O。  反應(yīng)流背壓(消費者消費負(fù)載過高時主動反饋生產(chǎn)者放慢生產(chǎn)速度的一種機(jī)制)。  具有高并發(fā)性,硬件資源消耗更少。  流暢的API設(shè)計。  同步和異步交互。  流式傳輸支持

HTTP底層庫選擇

Spring5的WebClient客戶端和WebFlux服務(wù)器都依賴于相同的非阻塞編解碼器來編碼和解碼請求和響應(yīng)內(nèi)容。默認(rèn)底層使用Netty,內(nèi)置支持Jetty反應(yīng)性HttpClient實現(xiàn)。同時,也可以通過編碼的方式實現(xiàn)ClientHttpConnector接口自定義新的底層庫;如切換Jetty實現(xiàn):

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

WebClient配置

基礎(chǔ)配置

WebClient實例構(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庫配置

通過定制Netty底層庫,可以配置SSl安全連接,以及請求超時,讀寫超時等

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è)置              connection.addHandlerLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS))                  .addHandlerLast(new WriteTimeoutHandler(10))          );          //連接超時設(shè)置          tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)          .option(ChannelOption.TCP_NODELAY,true);          return tcpClient;        });    WebClient.builder()        .clientConnector(new ReactorClientHttpConnector(httpClient))        .build();

編解碼配置

針對特定的數(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請求示例

uri構(gòu)造時支持屬性占位符,真實參數(shù)在入?yún)r排序好就可以。同時可以通過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請求示例

post請求示例演示了一個比較復(fù)雜的場景,同時包含表單參數(shù)和文件流數(shù)據(jù)。如果是普通post請求,直接通過bodyValue設(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)行多個調(diào)用,則更高效地方式是避免單獨阻塞每個響應(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)一修改攔截請求,比如認(rèn)證的場景,如下示例,filter注冊單個攔截器,filters可以注冊多個攔截器,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請求,請求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());

關(guān)于“Spring5中WebClient怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

網(wǎng)站名稱:Spring5中WebClient怎么用-創(chuàng)新互聯(lián)
網(wǎng)站鏈接:http://muchs.cn/article48/djjgep.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設(shè)、企業(yè)建站動態(tài)網(wǎng)站、網(wǎng)站收錄、App設(shè)計、品牌網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化