一、配置类缓存
1、引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
</dependencies>
2、写配置类
注意要注入容器
@Configuration
public class RedisConfig {
@Bean
public CacheManager cacheManager(LettuceConnectionFactory connectionFactory){
//定义序列化器
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer =
new GenericJackson2JsonRedisSerializer();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
//过期时间600秒
.entryTtl(Duration.ofSeconds(600))
// 配置序列化
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(stringRedisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(genericJackson2JsonRedisSerializer));
RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
3、 在具体方法上加@Cacheable
@Cacheable(value = "category", key = "'all'")
@Override
public List<Category> findCategoryTree() {
//这底下的是你查询的某些逻辑,根据自己的来写
List<Category> categoryList = categoryMapper.findAll();
List<Category> oneCategoryList = buildCategoryTree(categoryList, 0L);
return oneCategoryList;
}
4、启动类开启缓存
@EnableCaching
二、手动缓存
1、直接代码实现,因为很简单
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Override
public List<Category> findOneCategory() {
//1,从redis中查找一级分类
String categoryListJson = redisTemplate.opsForValue().get("category:one");
//判断查出来的是否存在,存在将json转成list返回
if (StringUtils.hasText(categoryListJson)){
List<Category> existCategoryList = JSON.parseArray(categoryListJson, Category.class);
return existCategoryList;
}
//没有将一级分类通过数据库查,并添加到redis中缓存
List<Category> categoryList = categoryMapper.findOneCategory();
redisTemplate.opsForValue().set("category:one",JSON.toJSONString(categoryList),60, TimeUnit.MINUTES);
return categoryList;
}
解释一下上面代码,首先直接从redis中读取category:one,查看是否有数据。如果有数据,把redis中的json数据转成list返回给前端。如果没有数据,那就设置
redisTemplate.opsForValue().set("category:one",JSON.toJSONString(categoryList),60, TimeUnit.MINUTES);category:one k
JSON.toJSONString(categoryList) v
60 过期时间
TimeUnit.MINUTES 时间单位
SpringCache学习链接 这个博主写的很好可以去看看