The right way to use Spring WebClient in a multi-threaded environment

I have one question regarding Spring WebClient

In my application, I need to make a lot of similar API calls, sometimes I need change headers in calls (authentication token). Therefore, the question arises, what would be the best of two options:

  • To create one WebClient for all incoming requests in MyService.class by making a field private final, for example, the code below:

    private final WebClient webClient = WebClient.builder()
            .baseUrl("https://another_host.com/api/get_inf")
            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
            .build();
    

Another question arises here: is WebClient safe? (since the service is used by many threads)

  1. To create a new WebClient for each new request that is part of the service class.

I want to ensure maximum performance and use it correctly, but I do not know how WebClient works inside it and how it will be used.

Thank.

+4
source share
1 answer

Two key points here WebClient:

  • Its HTTP resources (connections, caches, etc.) are managed by the underlying referenced library ClientHttpConnector, which you can configure toWebClient
  • WebClientand WebClient.Builderare immutable

ClientHttpConnector , - , , . , WebClient WebClient.create(). Spring Boot , WebClient.Builder bean, .

WebClient WebClient.Builder , , . WebClient , ( , Servlet).

, :

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

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

// 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();
+3

Source: https://habr.com/ru/post/1694429/


All Articles