redis缓存
public Article findById(String id) {
//查询数据查询数据库时
Article article = (Article)redisTemplate.opsForValue().get("Article_" + id);
if(article ==null){
//第一次访问redis数据库,如果为空
article =articleDao.findById(id).get();
//先存储到redis中
redisTemplate.opsForValue().set("Article_" + id,article,1,TimeUnit.DAYS);
}
//不为空时,直接从redis中读取,返回
return article;
}
cache结合redis缓存使用
启动类开启注解 @EnableCaching
查询时使用注解 @Cacheable(key ="#id",value ="gathering")
方法第一次使用缓存时,会在redis中寻找相应的key ,value ,如果有,存到redis,没有,就不存了
修改或删除时使用注解 @CacheEvict(key ="#gathering.id",value ="gathering") 清除缓存。