0

I am trying to use the spring-cache abstraction. In my case I want to cache a method call that produces a Mono.

My pom contains two dependencies:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
</dependencies>

With this dependencies (Spring boot parent 2.6.3) I have two very simple Services:

@Component
public class TestService1 {

    @Cacheable("testRequests1")
    public Mono<String> testMethodWrapper(String input) {
        return testMethod(input).cache();
    }

    public Mono<String> testMethod(String input) {
        System.out.println("uncached call on service1");
        return Mono.just("test1 " + input);
    }
}

and

@Component
public class TestService2 {


    public Mono<String> testMethodWrapper(String input) {
        return testMethod(input);
    }

    @Cacheable("testRequests2")
    public Mono<String> testMethod(String input) {
        System.out.println("uncached call on service2");
        return Mono.just("test2 " + input).cache();
    }
}

The difference is, that the in TestService1 the wrapper method is cached and in TestService2 the inner method. When I run my Spring Application:

@SpringBootApplication
@EnableCaching
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
        TestService1 testService1 = ctx.getBean(TestService1.class);
        TestService2 testService2 = ctx.getBean(TestService2.class);
        testService1.testMethodWrapper("test").block();
        testService1.testMethodWrapper("test").block();
        testService2.testMethodWrapper("test").block();
        testService2.testMethodWrapper("test").block();
    }
}

I get

2022-02-18 13:40:47.330  INFO 20240 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 1.8 seconds (JVM running for 2.793)
uncached call on service1
uncached call on service2
uncached call on service2

Why are calls to the method testMethod in the TestService2 not cached? What part from the Mono.cache() documentation:

Turn this Mono into a hot source and cache last emitted signals for further Subscriber.

did I not understand and how can I cache calls to testMethod in TestService2 that represents the scenario I need to implement?

Konrad Lötzsch
  • 467
  • 7
  • 15

0 Answers0