如何在spring-data 2.0.x中创建RedisCacheManager

我正在将应用程序从Spring Boot 1.5.x迁移到2.0.x。我想保留jedis,但我对的实例化有疑问RedisCacheManager

现在构造函数签名是

RedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration)

但在此之前:

RedisCacheManager(RedisOperations redisOperations)

我定义此bean仅RedisTemplate在范围内:

@Bean

public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {

HandleRedisCacheManager redisCacheManager = new HandleRedisCacheManager(redisTemplate);

redisCacheManager.setUsePrefix(true);

return redisCacheManager;

}

现在应该如何创建它?

回答:

它不再接受RedisTemplate。所以试试这个:

@Bean

public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory,

ResourceLoader resourceLoader) {

RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager

.builder(redisConnectionFactory)

.cacheDefaults(determineConfiguration(resourceLoader.getClassLoader()));

List<String> cacheNames = this.cacheProperties.getCacheNames();

if (!cacheNames.isEmpty()) {

builder.initialCacheNames(new LinkedHashSet<>(cacheNames));

}

return builder.build();

}

private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration(

ClassLoader classLoader) {

if (this.redisCacheConfiguration != null) {

return this.redisCacheConfiguration;

}

CacheProperties.Redis redisProperties = this.cacheProperties.getRedis();

RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

ObjectMapper mapper = new Jackson2ObjectMapperBuilder()

.modulesToInstall( new SimpleModule().addSerializer( new NullValueSerializer(null)) )

.failOnEmptyBeans( false )

.build();

mapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer( mapper );

//get the mapper b/c they registered some internal modules

config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));;

if (redisProperties.getTimeToLive() != null) {

config = config.entryTtl(redisProperties.getTimeToLive());

}

if (redisProperties.getKeyPrefix() != null) {

config = config.prefixKeysWith(redisProperties.getKeyPrefix());

config = config.computePrefixWith(cacheName -> redisProperties.getKeyPrefix() + cacheName + "::");

}

if (!redisProperties.isCacheNullValues()) {

config = config.disableCachingNullValues();

}

if (!redisProperties.isUseKeyPrefix()) {

config = config.disableKeyPrefix();

}

return config;

}

以上是 如何在spring-data 2.0.x中创建RedisCacheManager 的全部内容, 来源链接: utcz.com/qa/425032.html

回到顶部