DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Every Cache Miss Is a Tiny Tax on Your Performance
  • KV Cache Implementation Inside vLLM
  • The Bill You Didn't See Coming
  • Fine-Tuning of Spring Cache

Trending

  • Rust-Native Alternatives to Spark SQL and DataFrame Workloads
  • From "Vibe Coding" to Production: Setting Up an Evals Loop for Claude Agents
  • Testing Is Not About Finding Bugs
  • Amazon CodeWhisperer to Q Developer to Kiro: The Rise of Agentic Coding
  1. DZone
  2. Data Engineering
  3. Data
  4. Project Reactor and Caching With Caffeine

Project Reactor and Caching With Caffeine

Learn how to get Reactor playing with Caffeine.

By 
Biju Kunjummen user avatar
Biju Kunjummen
·
Mar. 24, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
10.4K Views

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. 

Java
 




x


 
1
Mono<String> get(String key) {
2
    Random random = ThreadLocalRandom.current();
3
    return Mono.fromSupplier(() -> key + random.nextInt());
4
}



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:

Java
 




x
16


 
1
public static <T> Function<String, Mono<T>> ofMono(@NotNull Duration duration,
2
                                                    @NotNull Function<String, Mono<T>> fn) {
3
    final Cache<String, T> cache = Caffeine.newBuilder()
4
            .expireAfterWrite(duration)
5
            .recordStats()
6
            .build();
7
 
          
8
    return key -> {
9
        T result = cache.getIfPresent(key);
10
        if (result != null) {
11
            return Mono.just(result);
12
        } else {
13
            return fn.apply(key).doOnNext(n -> cache.put(key, n));
14
        }
15
    };
16
}



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:

Java
 




x
22


 
1
Function<String, Mono<String>> fn = (k) -> get(k);
2
Function<String, Mono<String>> wrappedFn = CachingUtils.ofMono(Duration.ofSeconds(10), fn);
3
StepVerifier.create(wrappedFn.apply("key1"))
4
        .assertNext(result1 -> {
5
            StepVerifier.create(wrappedFn.apply("key1"))
6
                    .assertNext(result2 -> {
7
                        assertThat(result2).isEqualTo(result1);
8
                    })
9
                    .verifyComplete();
10
            StepVerifier.create(wrappedFn.apply("key1"))
11
                    .assertNext(result2 -> {
12
                        assertThat(result2).isEqualTo(result1);
13
                    })
14
                    .verifyComplete();
15
 
          
16
            StepVerifier.create(wrappedFn.apply("key2"))
17
                    .assertNext(result2 -> {
18
                        assertThat(result2).isNotEqualTo(result1);
19
                    })
20
                    .verifyComplete();
21
        })
22
        .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.

Cache (computing)

Published at DZone with permission of Biju Kunjummen. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Every Cache Miss Is a Tiny Tax on Your Performance
  • KV Cache Implementation Inside vLLM
  • The Bill You Didn't See Coming
  • Fine-Tuning of Spring Cache

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook