Project Reactor and Caching With Caffeine
Learn how to get Reactor playing with Caffeine.
Join the DZone community and get the full member experience.
Join For FreeSo you have a function that takes a key and returns a Project Reactor Mono type.
x
Mono<String> get(String key) {
Random random = ThreadLocalRandom.current();
return Mono.fromSupplier(() -> key + random.nextInt());
}
And you want to cache the retrieval of this Mono type by key. A good way to do that is to use the excellent Caffeine library. Caffeine natively does not support Reactor types, but it is fairly easy to use Caffeine with Reactor the following way:
x
public static <T> Function<String, Mono<T>> ofMono( Duration duration,
Function<String, Mono<T>> fn) {
final Cache<String, T> cache = Caffeine.newBuilder()
.expireAfterWrite(duration)
.recordStats()
.build();
return key -> {
T result = cache.getIfPresent(key);
if (result != null) {
return Mono.just(result);
} else {
return fn.apply(key).doOnNext(n -> cache.put(key, n));
}
};
}
It essentially wraps a function returning the Mono and uses Caffeine to get the value from a cache defined via a closure. If the value is present in the cache, it is returned. Otherwise, when the Mono emits a value, the value in the cache is set from that. So how can this be used? Here is a test with this utility:
x
Function<String, Mono<String>> fn = (k) -> get(k);
Function<String, Mono<String>> wrappedFn = CachingUtils.ofMono(Duration.ofSeconds(10), fn);
StepVerifier.create(wrappedFn.apply("key1"))
.assertNext(result1 -> {
StepVerifier.create(wrappedFn.apply("key1"))
.assertNext(result2 -> {
assertThat(result2).isEqualTo(result1);
})
.verifyComplete();
StepVerifier.create(wrappedFn.apply("key1"))
.assertNext(result2 -> {
assertThat(result2).isEqualTo(result1);
})
.verifyComplete();
StepVerifier.create(wrappedFn.apply("key2"))
.assertNext(result2 -> {
assertThat(result2).isNotEqualTo(result1);
})
.verifyComplete();
})
.verifyComplete();
Here I am using Project Reactor's StepVerifier utility to run a test on this wrapped function and ensure that the cached value is indeed returned for repeating keys. The full sample is available in this gist.
Published at DZone with permission of Biju Kunjummen, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments