Skip to content
thesarfo

Concept

Reactive: WebClient

Why WebClient replaces the blocking RestTemplate for inter-service calls, and a basic reactive HTTP request example.

views 0

Microservices don’t work alone — they always work as a group, so one microservice often calls another. An order service might need to check the user service, the inventory service, etc.

That means lots of network calls, so we need to send a request and get a response without keeping the thread in a waiting state — in other words, non-blocking asynchronous communication.

Spring Boot has RestTemplate for calling other services, but it’s blocking. We want something similar but reactive — that’s where WebClient comes in.

What is WebClient

A Reactor-based fluent API for making HTTP requests. It supports all HTTP methods, and lets you set headers, cookies, tokens, etc. It uses a builder pattern (base URL and so on), making it immutable. WebClient is also thread-safe.

A simple WebClient call:

@Test
public void blockTest() {
Response response = this.webClient
.get() // http request method
.uri("localhost:8080/reactive-math/square/{input}", 5) // exact url and path variables
.retrieve()
.bodyToMono(Response.class) // returns one object of type Response
.block(); // wait for the response to come back (for testing purposes)
System.out.println(response);
}