0

I'm trying to cache an authentication token response which is returned by a webclient call.

public Mono<Token> getToken() {
  return webclient.post().retrieve()
        .bodyToMono(Token.class)
        .cache(this::getTokenLiveDuration, t -> Duration.ZERO, () -> Duration.ZERO).log();
}

public Mono<MyResponse> execute() {
  return getToken().flatMap(token -> {
        webclient.post().header("Auth", token.getValue())
                 .retrieve()
                 .bodyToMono(MyResponse.class)
        }
}

But if I run execute() two time in a same instance, they have different tokens, which means the cache did not work.

What's the correct way of using .cache or the correct way to cache webclient response?

LunaticJape
  • 1,446
  • 4
  • 21
  • 39

1 Answers1

1

That's because each time getToken is called a new Mono is created with its own cache.

One way to make caching effective is creating a field for the cached token Mono and use that Mono in the execute method.

Martin Tarjányi
  • 8,863
  • 2
  • 31
  • 49