spring cache简介
Spring Cache使用方法与Spring对事务管理的配置相似。Spring Cache的核心就是对某
个方法进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用键值对的
方式存放到缓存中,当再次调用该方法使用相应的参数时,就会直接从缓存里面取出指
定的结果进行返回。
常用注解:
@Cacheable———-使用这个注解的方法在执行后会缓存其返回结果。
@CacheEvict————使用这个注解的方法在其执行前或执行后移除Spring Cache中的某些
元素。
spring cache的使用
(1)在springBoot项目的启动主程序上添加@EnableCache注解开启缓存支持
@SpringBootApplication@EnableCaching // 使用spring cache来做缓存,这是spring-context包中提供的,跟redis没啥关系public class GatheringApplication {public static void main(String[] args) {SpringApplication.run(GatheringApplication.class, args);}@Beanpublic IdWorker idWorker() {return new IdWorker(1, 1);}}
(2)在需要使用缓存的方法上使用@Cacheable注解来使用缓存,以参数为key,方法返回值为value_
/**
* 根据ID查询实体,使用spring cache做缓存处理
* @param id
* @return
*/
@Cacheable(value = "gathering", key = "#id")
public Gathering findById(String id) {
return gatheringDao.findById(id).get();
}
(3)在需要删除缓存的方法上使用@CacheEvict注解来删除缓存,key使用# + 如果是对象中的属性,通过.来获取属性
/**
* 修改 删除spring cache的缓存
*
* @param gathering
*/
@CacheEvict(value = "gathering", key = "#gathering.id")
public void update(Gathering gathering) {
gatheringDao.save(gathering);
}
