SpringBoot整合Redis缓存
本篇文章主要给大家介绍一下,如何在Spring Boot中整合Redis缓存
1. 添加依赖
添加spring-boot-starter-cache和spring-boot-starter-data-redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置
添加依赖注解后,在启动类上标注@EnableCaching。通过一下代码配置CacheManager:
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
// 修改key间隔,默认为双引号
.computePrefixWith(name -> name + ":")
// 序列化策略,使用Jackson序列化
.serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
// 缓存过期时间
.entryTtl(Duration.ofDays(7));
}
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
// 设置key序列化方式string,RedisSerializer.string() 等价于 new StringRedisSerializer()
redisTemplate.setKeySerializer(RedisSerializer.string());
// 设置value的序列化方式json,使用GenericJackson2JsonRedisSerializer替换默认序列化,RedisSerializer.json() 等价于 new GenericJackson2JsonRedisSerializer()
redisTemplate.setValueSerializer(RedisSerializer.json());
// 设置hash的key的序列化方式
redisTemplate.setHashKeySerializer(RedisSerializer.string());
// 设置hash的value的序列化方式
redisTemplate.setHashValueSerializer(RedisSerializer.json());
// 使配置生效
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
3. 用法
@Service
public class ItemService {
private final ItemRepository itemRepository;
public ItemService(ItemRepository itemRepository) {
this.itemRepository = itemRepository;
}
// 使用@Cacheable注解来标记该方法的返回值应该被缓存
@Cacheable(value = "item", key = "#id")
public Optional<Item> getItemById(Long id) {
return itemRepository.findById(id);
}
}