Communication Between Microservices | Spring WebClient

Sandaka Geethaj Wijesinghe
2 min readJul 1, 2022

Spring WebClient is a non-blocking and reactive web client to perform HTTP requests. WebClient has been introduced in Spring 5 with the spring-webflux module and provides a fluent functional style API. The primary method for client-side HTTP accesses within the Spring MVC project prior to Spring 5 was RestTemplate.

We’ll go over how to configure the Spring WebClient and implement it to send GET, POST, and other HTTP requests. Additionally, we will discover how to set up the client to handle timeouts and other HTTP-related configurations.

WebClient vs RestTemplate

RestTemplate has been available from Spring as a web client abstraction for a while. The Java Servlet API, which is built on the thread-per-request architecture, is what powers the RestTemplate. As a result, the thread will be blocked until the web client has received the response. The blocked code has an issue because each thread uses a certain amount of memory and CPU time.

WebClient will produce something similar to a “thread” for each event, whereas RestTemplate uses the caller thread for each event (HTTP call). These “threads” will be placed in a queue by the Reactive framework, which will only execute them out when the proper response is available. The Reactive Streams API, offers a way for asynchronous functionality to be composed with event-driven architecture that has been used by the reactive framework.

We will add the WebClient as a necessary dependency for Spring Reactive support because it is a component of the spring-webflux module.

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

WebClient Configuration

Here we’ll see how to define web client configuration with a certain time out. We can configure the WebClient’s connection timeout in a method similar to that of the Spring RestTemplate. To configure the client’s timeout, use the HttpClient class.

Here we’ll Initialize the client with base URI, cookie, and header configurations.

Requests Handling with Spring WebClient

Here you can see how to implement the routes to GET and POST requests through the WebClient. If your application is running on port 8080, you can test the request on postman using

http://localhost:8080/api/posts/<post-id>

and try the other routes using a similar manner by providing relevant parameters.

When you are making a request, the data will retrieve from the other service that we have configured in WebClientConfig

In this article, We learned on how to set up, configure, and use WebClient. In addition, learned how to configure your client’s timeout settings as well.

Great! you have done.

Appreciate your feedback. Thank you!

--

--

Sandaka Geethaj Wijesinghe

Software Engineer | Content Creator | MSc in SE (UK), BIT (UCSC), CMJD/ABSD (IJSE)