13

I'm a beginner of spring webflux. While researching I found some code like:

Mono result = someMethodThatReturnMono().cache();

The name "cache" tell me about caching something, but where is the cache and how to retrieve cached things? Is it something like caffeine?

SoT
  • 898
  • 1
  • 15
  • 36
  • Your mono is a rawtype - don’t do that. Read the docs please - every subscriber to a Mono would normally trigger a new subscription; when `cache` is called then once a value is returned, the same value will be returned to all subsequent subscribers. https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#cache-- – Boris the Spider May 11 '21 at 12:57

1 Answers1

23

It cache the result of the previous steps of the Flux/Mono until the cache() method is called, check the output of this code to see it in action:

import reactor.core.publisher.Mono;

public class CacheExample {

    public static void main(String[] args) {
        var mono = Mono.fromCallable(() -> {
            System.out.println("Go!");
            return 5;
        })
        .map(i -> {
            System.out.println("Double!");
            return i * 2;
        });

        var cached = mono.cache();

        System.out.println("Using cached");

        System.out.println("1. " + cached.block());
        System.out.println("2. " + cached.block());
        System.out.println("3. " + cached.block());

        System.out.println("Using NOT cached");


        System.out.println("1. " + mono.block());
        System.out.println("2. " + mono.block());
        System.out.println("3. " + mono.block());
    }
}

output:

Using cached
Go!
Double!
1. 10
2. 10
3. 10
Using NOT cached
Go!
Double!
1. 10
Go!
Double!
2. 10
Go!
Double!
3. 10
rascio
  • 8,968
  • 19
  • 68
  • 108
  • But for how long by default does this `cache` work ? https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#cache-- `Once the first subscription is made to this Mono, the source is subscribed to and the signal will be cached, indefinitely. This process cannot be cancelled.` It's `indefinitely` ? – tryingHard Nov 25 '22 at 12:03
  • yes, it is. It doesn't have a time to live, this is used for different use cases. Imagine during the handling of a request for an http server, or during the running of a batch you have to access the same calculation multiple time, but you want to calculate it only once. – rascio Nov 25 '22 at 20:37
  • ok, but when i use HTTP request with other param value will the cache return the same result ? For example `calculations` are done based on some kind of param that is provided in http request. – tryingHard Nov 28 '22 at 07:55
  • 2
    nope I meant calculations in the scope of the same HTTP request, not shared among multiple HTTP requests. To implement a cache across different requests you need some other caching mechanism, the Mono/Flux cache is something also named **memoization** in other contexts – rascio Nov 28 '22 at 10:14