Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use WebClient in Spring5

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to use WebClient in Spring5. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Preface

Spring5 brings a new responsive web development framework, WebFlux, and also introduces a new HttpClient framework, WebClient. WebClient is a non-blocking, reactive client introduced in Spring5 to execute HTTP requests. It has good support for both synchronous and asynchronous as well as streaming solutions. After WebClient is released, RestTemplate will be deprecated in future releases, and major new features will not be added forward.

Comparison between WebClient and RestTemplate

WebClient is a full-featured Http request client. Compared with RestTemplate, WebClient supports the following:

Non-blocking I PUBO. Reaction flow back pressure (a mechanism by which consumers actively feedback producers to slow down production when the consumption load is too high). It has high concurrency and less hardware resource consumption. Smooth API design. Synchronous and asynchronous interactions. Streaming support

HTTP underlying library selection

Both Spring5's WebClient client and WebFlux server rely on the same nonblocking codec to encode and decode request and response content. The default underlying layer is Netty, with built-in support for Jetty reactive HttpClient implementation. At the same time, you can also implement the ClientHttpConnector API to customize the new underlying library by coding, such as switching Jetty implementation:

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

WebClient configuration

Basic configuration

The WebClient instance constructor can set some basic global web request configuration information, such as default cookie, header, baseUrl, etc.

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 library configuration

By customizing the Netty underlying library, you can configure SSl secure connections, request timeout, read and write timeout, etc.

HttpClient httpClient = HttpClient.create () .secure (sslContextSpec-> {SslContextBuilder sslContextBuilder = SslContextBuilder.forClient () .trustManager (new File ("E://server.truststore")); sslContextSpec.sslContext (sslContextBuilder);}) .tcpConfiguration (tcpClient-> {tcpClient.doOnConnected (connection-> / / read and write timeout setting connection.addHandlerLast (new ReadTimeoutHandler (10, TimeUnit.SECONDS)) .addHandlerLast (new WriteTimeoutHandler (10) / / connection timeout sets tcpClient.option (ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option (ChannelOption.TCP_NODELAY,true); return tcpClient;}); WebClient.builder () .clientConnector (new ReactorClientHttpConnector (httpClient)) .build ()

Codec configuration

For a specific data interaction format, you can set a custom encoding and decoding mode, as follows:

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

Example of get request

Attribute placeholders are supported when uri is constructed, and the real parameters can be sorted when entering parameters. At the same time, you can set the media type and encoding through accept. The final result value is received through Mono and Flux, and the return value is subscribed in the subscribe method.

WebClient client = WebClient.create ("http://www.kailing.pub"); Mono result = client.get () .uri (" / article/index/arcid/ {id} .html ", 256) .attributes (attr-> {attr.put (" name "," kl "); attr.put (" age "," 28 ");}) .accountCharset (StandardCharsets.UTF_8) .accept (MediaType.TEXT_HTML) .accept () .bodyToMono (String.class) Result.subscribe (System.err::println)

Example of post request

The post request example demonstrates a more complex scenario that contains both form parameters and file stream data. If it is an ordinary post request, you can set the object instance directly through bodyValue. No FormInserter construction.

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 result = client.post () .uri ("/ article/index/arcid/ {id} .html", 256) .contentType (MediaType.APPLICATION_JSON) .body (formInserter) / / .bodyValue (ImmutableMap.of ("name", "kl")) .kl () .bodyToMono (String.class); result.subscribe (System.err::println)

Synchronize the returned result

All shown above are asynchronous subscription response values via mono's subscribe. Of course, if you want to synchronize blocking to get the results, you can also block the current thread to get the return value.

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

However, if multiple calls are required, it is more efficient to avoid blocking each response individually and instead wait for the combined result, such as:

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

Filter filter

You can modify intercept requests uniformly by setting filter interceptors, such as authentication scenarios. For example, filter registers a single interceptor, filters can register multiple interceptors, basicAuthentication is the built-in interceptor for basicAuth, and limitResponseSize is the interceptor built in the system to limit the size of the response byte.

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

Websocket support

WebClient does not support websocket requests. WebSocketClient is required when requesting websocket interfaces, such as:

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

This is the end of the article on "how to use WebClient in Spring5". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report