SpringCatch
1、在SpringBoot中的使用
(1)为Application启动类添加@EnableCaching开启缓存支持
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(GatheringApplication.class, args);
}
}
(2)在对应Service的findById方法添加缓存注解,这样当此方法第一次运行,在缓存中没有找到对应的value和key,则将查询结果放入缓存
@Cacheable(value = "gathering", key = "#id")
public Gathering findById(String id) {
return gatheringDao.findById(id).get();
}
特例:多个字段同时作为key
@Cacheable(value = "gathering", key = "#type+'-'+#code+'-'+#description")
public Object getDicByTypeAndCode(int type, Integer code, Boolean description) {
...
}
(3)在修改与删除时,需要删除缓存。
@CacheEvict(value = "gathering", key = "#gathering.id")
public void update(Gathering gathering) {
gatheringDao.save(gathering);
}
@CacheEvict(value = "gathering", key = "#id")
public void deleteById(String id) {
gatheringDao.deleteById(id);
}
不能设置过期时间,所以在不需要过期时间时使用。