Right way to use Spring WebClient in multi-thread environment

Two key things here about WebClient:

  1. Its HTTP resources (connections, caches, etc) are managed by the underlying library, referenced by the ClientHttpConnector that you can configure on the WebClient
  2. WebClient is immutable

With that in mind, you should try to reuse the same ClientHttpConnector across your application, because this will share the connection pool – this is arguably the most important thing for performance. This means you should try to derive all WebClient instances from the same WebClient.create() call. Spring Boot helps you with that by creating and configuring for you a WebClient.Builder bean that you can inject anywhere in your app.

Because WebClient is immutable it is thread-safe. WebClient is meant to be used in a reactive environment, where nothing is tied to a particular thread (this doesn’t mean you cannot use in a traditional Servlet application).

If you’d like to change the way requests are made, there are several ways to achieve that:

configure things in the builder phase

WebClient baseClient = WebClient.create().baseUrl("https://example.org");

configure things on a per-request basis

Mono<ClientResponse> response = baseClient.get().uri("/resource")
                .header("token", "secret").exchange();

create a new client instance out of an existing one

// mutate() will *copy* the builder state and create a new one out of it
WebClient authClient = baseClient.mutate()
                .defaultHeaders(headers -> {headers.add("token", "secret");})
                .build();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)