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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Why GPUs Run at 40% in LLM Inference and How To Fix It
  • Prompt Caching for Multi-Turn Coding Agents: Why Append-Only Transcripts Cut Your Token Bill
  • Prompt Caching for LLMs, Part 3: Model-Side Caching and Production Rollout
  • Prompt Caching for LLMs, Part 2: Semantic Caching in Production

Trending

  • Build Production-Ready AI Phone Agents: Infrastructure, Models, and Telephony
  • Hosted Code Interpreter in Spring AI: Letting OpenAI Write and Run Python via the Responses API
  • AI-Assisted Product Discovery
  • Integrating Jev via REST With Java and Spring RestClient

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Mar. 24, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
10.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Why GPUs Run at 40% in LLM Inference and How To Fix It
  • Prompt Caching for Multi-Turn Coding Agents: Why Append-Only Transcripts Cut Your Token Bill
  • Prompt Caching for LLMs, Part 3: Model-Side Caching and Production Rollout
  • Prompt Caching for LLMs, Part 2: Semantic Caching in Production

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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