Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wise to create Webclient again and again in Webflux since my base URI is not fixed?

In my microservice I have to fetch data from places. Some of the URL's are fixed but some are not . So do I need to create Webclient again and again if my base URL changes. If not then is the below way correct to create Web Client. WebClient.create(); and later changing the URI again and again whenever I make a call. As per my understanding creating a WebClient must be some heavy operation.

ReactorClientHttpConnector connector = new ReactorClientHttpConnector(
                options -> options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, requestTimeout).compression(true)
                        .afterNettyContextInit(ctx ->  ctx.addHandlerLast(new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS))));
        return WebClient.builder()
                        .clientConnector(connector)
                        .baseUrl(hostURL)
                        .build();
like image 912
naval jain Avatar asked Dec 19 '18 04:12

naval jain


1 Answers

WebClient instances are meant to be reusable. The only reason you'd need to have different client instances is for specific needs: instrumentation for observability, specific authentication client filters, specific connection/read/write timeouts.

Different base URIs is not a strong reason to create different instances. It's perfectly fine to create an instance and not set a base URI, it's merely a convenience to avoid duplication when calling the same host over and over again.

This is perfectly fine:

WebClient webClient = WebClient.builder().build();

Mono<Resource> resource = webClient.get().uri("http://example.org/resource").retrieve()...;
Mono<Project> project = webClient.get().uri("http://spring.io/projects/spring-boot").retrieve()...;

Note that if you use Spring Boot, you should instead consider building your webclient instance using the provided WebClient.Builder (see the Spring Boot reference documentation).

like image 151
Brian Clozel Avatar answered Nov 10 '22 18:11

Brian Clozel