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 Free
So you have a function that takes a key and returns a Project Reactor Mono type.
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:
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:
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.