Spring Webflux WebClient

A client for making HTTP requests is included in Spring WebFlux. The Reactor-based WebClient API allows a declarative mixture of asynchronous functionality without requiring knowledge of threads or concurrency. Depending on the same used to encode and decode request and response content on the server side, it is non-blocking and allows streaming.

Example of Spring Webflux WebClient:

WebClient client = WebClient.create("http://localhost:8080");
client
.get()
.uri("/posts")
.exchange()
.flatMapMany(res -> res.bodyToFlux(Post.class))
.log()
.subscribe(post -> System.out.println("post: " + post));

Implementation of Spring Webflux WebClient

Below are the steps to implement Spring Webflux WebClient.

Step 1: Add Maven Dependencies

Let’s update the pom.xml file with the ensuing dependencies:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

Step 2: Create a WebClient Instance

There are three alternatives available. Making a WebClient object with default settings is the first step.

WebClient client = WebClient.create();

Starting a WebClient instance with a specified base URI is the second option:

WebClient client = WebClient.create("http://localhost:port_number");

Step 3: Build a client using the DefaultWebClientBuilder

Using the DefaultWebClientBuilder class to build a client allows for complete customisation, making it the third and most advanced option:

WebClient client = WebClient.builder()
.baseUrl("http://localhost:port_number")
.defaultCookie("cookieKey", "cookieValue")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.defaultUriVariables(Collections.singletonMap("url", "http://localhost:port_number"))
.build();

Step 4: Create a WebClient Instance with Timeouts

The 30-second HTTP timeouts that are set by default are frequently too sluggish for our purposes. We can change this behaviour by creating an instance of HttpClient and configuring our WebClient to use it.

Java
// Create an instance of HttpClient with custom configurations
HttpClient httpClient = HttpClient.create()
  // Set the connection timeout to 3000 milliseconds
  .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
  // Set the response timeout to 3000 milliseconds
  .responseTimeout(Duration.ofMillis(3000))
  // Add handlers for read and write timeouts
  .doOnConnected(conn -> 
    conn.addHandlerLast(new ReadTimeoutHandler(3000, TimeUnit.MILLISECONDS))
      .addHandlerLast(new WriteTimeoutHandler(3000, TimeUnit.MILLISECONDS)));

// Create a WebClient with a ReactorClientHttpConnector using the configured HttpClient
WebClient client = WebClient.builder()
  .clientConnector(new ReactorClientHttpConnector(httpClient))
  .build();