Is it a good idea to cache webclient creation

Viewed 294

I am using spring webclient to call external APIs. I have a builder which returns webclient. My question, is that a good idea to cache the created webclient for a specific URL.Below is my code.

@Cacheable(value = "somevalue", cacheManager = "cachemnager", key = "#url")
public WebClient getWebClient(String url, Map<String, String> headers,List<ExchangeFilterFunction> filterFunctions) {
        return WebClient.builder()
            .baseUrl(url)
            .defaultHeaders(addsome headers)
            .filters(list -> list.addAll(filterFunctions))
            .build();
}

Also I have to call multiple API with different url/params/headers so I have to create multiple webclient as well.

1 Answers

Bad idea to me because :

  1. spring-boot already auto-configures a WebClient.Builder for you. It also pre-configured default codec in this builder for converting HTTP request/reponse to/from different type of java object. Creating it by yourself means that you need to configure this stuff by yourself.

  2. If you really want to do it, it is overkill to use spring cache abstraction because most probably an application does not need to create many WebClient that will cause the JVM has the chance to run out of memory. So you do not need the expiration and eviction feature provided by the cache , just use a simple HashMap to keep it simple.

The official docs strongly advises to inject the pre-configured WebClient.Builder to create and configure the WebClient. So just follow it . Also see the docs for an example for how to do it.

Related