案例:
在启动类上加注解:@EnableCaching
@SpringBootApplication
@EnableCaching
public class GatheringApplication {
public static void main(String[] args) {
SpringApplication.run(GatheringApplication.class, args);
}
}
在service方法上使用注解:@Cacheable
添加缓存
/**
* 根据ID查询实体
* @param id
* @return
* 通过参数id找当前方法的返回值
*/
@Cacheable(value = "gathering", key = "#id")
public Gathering findById(String id) {
return gatheringDao.findById(id).get();
}
在service方法上使用注解:@CacheEvict
删除一个缓存
/**
* 修改
* @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);
}