帮我写一个springboot整合redis缓存的配置类
时间: 2023-03-28 19:01:12 浏览: 123
好的,我可以回答这个问题。以下是一个简单的Spring Boot整合Redis缓存的配置类:
```
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
}
}
```
这个配置类使用了Spring Boot提供的@EnableCaching注解来启用缓存功能,并且定义了一个RedisTemplate和一个CacheManager来管理缓存。其中,RedisTemplate用于操作Redis,CacheManager用于管理缓存。同时,我们还配置了Redis的序列化方式为JSON格式,并设置了缓存的过期时间为10分钟。
阅读全文