gpt4 book ai didi

java - 响应式(Reactive)应用程序中的 Spring Cache

转载 作者:行者123 更新时间:2023-12-05 04:52:00 25 4
gpt4 key购买 nike

我正在使用 Spring Cache 默认实现(ConcurrentHashMap):

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

react 器 addons用于获取元素。在缓存未命中时,将项目写入缓存:

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); 是否被视为阻塞调用?应该在不同的调度程序上发布吗?

最佳答案

是的。

如果有机会,我建议您将 ReactiveRedisConnection 与 Lettuce 一起使用相反。

例如,您可以按如下方式设置 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))
));

关于java - 响应式(Reactive)应用程序中的 Spring Cache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66628299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com