Marcus Lindwall
Marcus Lindwall

Reputation: 325

Eagerly caching Mono

I'm looking to eagerly cache the results of a Reactor Mono. It's scheduled to be updated in cache every 10 minutes, but since the Mono is only evaluated when subscribed to, the task doesn't actually refresh the cache.

Example:

@Scheduled(fixedRate = 10 * 60 * 1000 + 3000)
fun getMessage(): Mono<String> {
    return Mono.just("Hello")
            .map { it.toUpperCase() }
            .cache(Duration.ofMinutes(10))
}

Upvotes: 0

Views: 2275

Answers (1)

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28301

You need to store your Mono somewhere, otherwise each invocation of the method (through the Scheduled or directly) will return a different instance.

Perhaps as a companion object?

Here is how I would do it naïvely in Java:

protected Mono<String> cached;

//for the scheduler to periodically eagerly refresh the cache
@Scheduled(fixedRate = 10 * 60 * 1000 + 3000)
void refreshCache() {
    this.cached = Mono.just("Hello")
            .map { it.toUpperCase() }
            .cache(Duration.ofMinutes(10));
    this.cached.subscribe(v -> {}, e -> {}); //swallows errors during refresh
}

//for users
public Mono<String> getMessage() {
    return this.cached;
}

Upvotes: 1

Related Questions