Spring Cache in a reactive application

Viewed 1421

I am using the Spring Cache default implementation(ConcurrentHashMap):

@Bean
CacheManager cacheManager() {
    ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager("mycache");
    cacheManager.setAllowNullValues(false);
    return cacheManager;
}

Reactor addons is used to get an item. On cache miss item is written to the cache:

public Mono<T> get(ID key) {
    return CacheMono.lookup(k -> findValue(k).map(Signal::next), key)
                    .onCacheMissResume(Mono.defer(valueRetriever(key)))
                    .andWriteWith((k, signal) -> Mono.fromRunnable(() -> {
                        if (!signal.isOnError()) {
                            writeValue(k, signal.get());
                        }
                    }));
}

private void writeValue(ID key, T value) {
    if (value != null) {
        cache.put(key, value);
    }
}

Does cache.put(key, value); considered a blocking call? Should be published on a different Scheduler?

1 Answers

Yes.

If you have the opportunity, I would suggest you to use ReactiveRedisConnection with Lettuce instead.

You could for example setup your beans as follows:

@Bean
public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() {
    final RedisStandaloneConfiguration redisConfig 
    = new RedisStandaloneConfiguration(SpringBootApp.redisHost, SpringBootApp.redisPort);
    redisConfig.setPassword(SpringBootApp.redisPassword);
    redisConfig.setDatabase(0);
    final LettuceConnectionFactory connFac = new LettuceConnectionFactory(redisConfig);
    return connFac;
}

@Bean
public ReactiveRedisConnection reactiveRedisConnection(final ReactiveRedisConnectionFactory redisConnectionFactory) {
    return redisConnectionFactory.getReactiveConnection();
}

@Bean
public ReactiveRedisOperations<String, Object> redisOperations(ReactiveRedisConnectionFactory factory) {
    final JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
    final RedisSerializationContext.RedisSerializationContextBuilder<String, Object> builder = RedisSerializationContext
            .newSerializationContext(new StringRedisSerializer());
    final RedisSerializationContext<String, Object> context = builder.value(serializer).build();
    return new ReactiveRedisTemplate<>(factory, context);
}

Then you can use ReactiveRedisOperations to store/retrieve your data from your cache non-blocking. You could do something like:

   Mono.just("my_cache_key::" + uniqueId)
                .flatMap(key ->  reactiveRedisOps.opsForValue().get(key)
                        .cast(MyObj.class)
                        .switchIfEmpty(
                          getMyObjNonBlocking()
                           .flatMap(myObj -> ops.opsForValue().set(key, myObj, 
                                            Duration.ofMinutes(ttl))
                                            .thenReturn(myObj))
                        ));
Related