急切地缓存单声道



我正在寻找急切地缓存Reactor Mono的结果。它计划每 10 分钟在缓存中更新一次,但由于 Mono 仅在订阅时进行评估,因此该任务实际上不会刷新缓存。

例:

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

Mono存储在某个地方,否则该方法的每次调用(通过Scheduled或直接(将返回不同的实例。

也许作为伴侣对象?

以下是我在 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;
}

最新更新