Spring全家桶+分布式微服务(十次方项目学习)
十次方学习交流qq群:672373393
其实在sptringboot中本身提供了一个缓存SpringCache,相比redis更加的简单,但是相对的功能也没有redis强大。如果没有其它特别的需求,比如说设定缓存时间等。那么我们就可以直接使用springcache将会更加简单,多用于find查询中。
如何使用?
1.在启动类上添加注解
@EnableCaching //表示我要使用springboot的缓存 springcache
2. 上代码
我们还是那findById来说,springcache直接在方法上加上注解
@Cacheable 其中参数value是作为全局唯一id,key则是作为value中的子id,两个参数都必须要写 这里注意用#可以拿到方法参数值 #后面接参数名就可以了
/**
* 根据ID查询实体
* @param id
* @return
*/
@Cacheable(value = "gathering",key = "#id") //存springcache,value表示在cache中全局名称,key才是id,用#可以拿到参数值
public Gathering findById(String id) {
return gatheringDao.findById(id).get();
}
同理,我们如果对数据进行了修改,也需要更改缓存中的数据,这里用到注解
@CacheEvict 参数与@Cacheable一致
/**
* 修改
* @param gathering
*/
@CacheEvict(value = "gathering",key = "#gathering.id")
public void update(Gathering gathering) {
gatheringDao.save(gathering);
}
/**
* 删除
* @param id
*/
@CacheEvict(value = "gathering",key = "#id")
public void deleteById(String id) {
gatheringDao.deleteById(id);
}