Cache the result of a Mono from a WebClient call in a Spring WebFlux web application

前端 未结 2 867
予麋鹿
予麋鹿 2020-12-16 04:23

I am looking to cache a Mono (only if it is successful) which is the result of a WebClient call.

From reading the project reactor addons docs I don\'t

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 05:01

    Actually, you don't have to save errors with CacheMono.

    private Cache myCaffeineCache;
    
    ...
    
    Mono myResponseObject =
            CacheMono.lookup(key -> Mono.justOrEmpty(myCaffeineCache.getIfPresent(key))
                    .map(Signal::next), myRequestObject)
                    .onCacheMissResume(() -> /* Your web client or other Mono here */)
                    .andWriteWith((key, signal) -> Mono.fromRunnable(() ->
                            Optional.ofNullable(signal.get())
                                    .ifPresent(value -> myCaffeineCache.put(key, value))));
    

    When you switch to external cache, this may be usefull. Don't forget using reactive clients for external caches.

提交回复
热议问题