RedisTemplate配置
时间: 2023-07-04 08:04:14 浏览: 239
在使用Spring Boot时,可以通过如下配置类来配置RedisTemplate:
```java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
}
}
```
其中,`redisTemplate`方法用于创建一个`RedisTemplate`实例,同时配置了默认的key和value的序列化方式为`StringRedisSerializer`和`GenericJackson2JsonRedisSerializer`。
`cacheManager`方法用于创建一个`CacheManager`实例,并配置了默认的key和value的序列化方式为`StringRedisSerializer`和`GenericJackson2JsonRedisSerializer`,同时设置了缓存的过期时间为10分钟,并禁用了缓存空值。
阅读全文