Spring Cache使用方法与Spring对事务管理的配置类似。Spring Cache的核心就是对某 个方法进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用键值对的 方式存放到缓存中,当再次调用该方法使用相应的参数时,就会直接从缓存里面取出指 定的结果进行返回redis
相比于redis,springcache没有设置缓存过时时间的功能spring
使用步骤:缓存
一、在springboot启动类上加注解:@EnableCachingspringboot
二、使用@Cacheable注解,使被注解的查询方法加入缓存:spa
@Cacheable(value = "gathering",key = "#id") public Gathering findById(String id) { return gatheringDao.findById(id).get(); }
其中value是大key,key是小key,至关于redis的hash类型。#是关键字,表示从方法形参(id)中取值code
三、使用@CacheEvict注解,令缓存失效:blog
@CacheEvict(value = "gathering",key = "#id") public void deleteById(String id) { gatheringDao.deleteById(id); }
@CacheEvict(value = "gathering",key = "#gathering.id") public void update(Gathering gathering) { gatheringDao.save(gathering); }