spring缓存

kpbwa7wx  于 2021-07-22  发布在  Java
关注(0)|答案(1)|浏览(398)

我使用的是spring缓存默认实现(concurrenthashmap):

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

reactor插件用于获取项目。缓存未命中项写入缓存:

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);
    }
}

cache.put(key, value); 被认为是阻拦电话?是否应在其他计划程序上发布?

4uqofj5v

4uqofj5v1#

对。
如果你有机会,我建议你用reactiveredisconnection代替莴苣。
例如,您可以按如下方式设置bean:

@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);
}

那你可以用 ReactiveRedisOperations 以非阻塞方式从缓存中存储/检索数据。你可以这样做:

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))
                        ));

相关问题