0

I am trying to use Spring Boot CacheManager with Caffeine and some @Cacheable annotated functions. In our tests, asynchronous calls to our controllers endpoints are having issues that seem to be related to the fact that we were using a non-asynchronous cache.

While doing some research, I have seen a lot of examples of using Caffeine manually with CompletableFuture, but could not found nothing with AsyncCacheLoader and Spring Boot CacheManager and @Cacheable annotation. It looks like Cache and AsyncCache have very distinct APIs. Is this possible to use the default Spring Boot CacheManager asynchronously?

Thanks!

Béatrice Cassistat
  • 1,048
  • 12
  • 37

1 Answers1

1

Updating the answer after comment by Ben Manes. You can use @Cacheable with Spring Boot Cache Manager for reactive Spring Webflux but underneath the hoods values are stored in synchronous cache. Here is an example

@RestController
@SpringBootApplication
@EnableCaching
public class GatewayApplication {

 @PostMapping(value ="/test", produces = "application/json")
 public Flux<String> handleRequest(@RequestBody String body) {
    return getData(body);
 }

 @Cacheable("cache")
 private Flux<String> getData(String body) {
    return WebClient.create().post()
            .uri("http://myurl")
            .body(BodyInserters.fromObject(body))
            .retrieve().bodyToFlux(String.class).cache();
 }
}

As you can see in above example, its using Spring Webflux(Project reactor) and @Cacheable method returns Flux which is async.

You can use AsyncCache directly if you want reactive cache as it stores CompleteableFutures

Avik Kesari
  • 271
  • 2
  • 13
  • I believe this stores into a synchronous cache (Spring [#26713](https://github.com/spring-projects/spring-framework/issues/26713)). Their caching support of reactive types is still an open issue (Spring [#17920](https://github.com/spring-projects/spring-framework/issues/17920)). – Ben Manes Oct 28 '21 at 21:33