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 configure WebClient for Spring5

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to configure WebClient in Spring5". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to configure WebClient with Spring5.

The 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. Compared with 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 ("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 ())

The underlying layer depends on the Netty library configuration

By customizing the Netty underlying library, you can configure SSl secure connections, request timeouts, read and write timeouts, and so on. One thing to note here is that the default connection pool has a maximum connection of 500. The default for getting connection timeout is 45000ms. You can configure it as a dynamic connection pool to break through these default configurations, or you can make your own configuration based on the business. Select threads and worker threads, including Netty, can also be set on their own.

/ / configure dynamic connection pool / / ConnectionProvider provider = ConnectionProvider.elastic ("elastic pool"); / / configure fixed size connection pool, such as maximum number of connections, connection acquisition timeout, idle connection death time, etc. 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-> {/ / specify the number of select and work threads for Netty LoopResources loop = LoopResources.create ("kl-event-loop", 1, 4, true) Return tcpClient.doOnConnected (connection-> {/ / read / write timeout setting connection.addHandlerLast (new ReadTimeoutHandler (10, TimeUnit.SECONDS)) .addHandlerLast (new WriteTimeoutHandler (10));}) / / connection timeout set.option (ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option (ChannelOption.TCP_NODELAY, true) .runOn (loop);}) 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 () .codecs (new Jackson2JsonDecoder ()); configurer.customCodecs () .encoder (new Jackson2JsonEncoder ());}) .build (); WebClient.builder () .exchangeStrategies (strategies) .build (); get request example

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) .accountCharset (StandardCharsets.UTF_8) .accept (MediaType.TEXT_HTML) .resume () .bodyToMono (String.class); result.subscribe (System.err::println)

If you need to carry complex query parameters, you can construct the uri request address through UriComponentsBuilder, such as:

/ / define query parameters MultiValueMap params = new LinkedMultiValueMap (); params.add ("name", "kl"); params.add ("age", "19"); / / define url parameters Map uriVariables = new HashMap (); uriVariables.put ("id", 200); String uri = UriComponentsBuilder.fromUriString ("/ article/index/arcid/ {id} .html")

When downloading files, you can set accept to MediaType.ALL because you are not clear about the MIME Type of files in various formats, and then use the Resource of Spring to receive data, such as:

WebClient.create ("https://kk-open-public.oss-cn-shanghai.aliyuncs.com/xxx.xlsx"). Get () .accept (MediaType.ALL) .subscribe () .bodyToMono (Resource.class) .subscribe-> {try {File file = new File (" E://abcd.xlsx "); FileCopyUtils.copy (StreamUtils.copyToByteArray (resource.getInputStream ()), file) } catch (IOException ex) {}}); post request example

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); return result synchronously

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);}) .destroy (filters-> {filters.add (" username "," password ")) Filters.add (ExchangeFilterFunctions.limitResponseSize);}) .build () .get () .uri ("/ article/index/arcid/ {id} .html", 254) .subscription () .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 ()); now that you have a better understanding of "how Spring5 configures WebClient", you might as well do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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