1、在SpringBoot的启动类上添加注解@EnableCaching
,开启SpringCache缓存支持
@SpringBootApplication
// 开启SpringCache缓存支持
@EnableCaching
public class GatheringApplication {
public static void main(String[] args) {
SpringApplication.run(GatheringApplication.class, args);
}
}
2、在service的方法上添加对应的注解
/** * 根据ID查询 * * @param id * @return */
// 使用SpringCache进行缓存数据库查询
@Cacheable(value = "gathering", key = "#id")
public Gathering findById(String id) {
return gatheringDao.findById(id).get();
}
/** * 修改 * * @param gathering */
// 修改数据库数据后需要删除redis中的缓存
@CacheEvict(value = "gathering", key = "#gathering.id")
public void update(Gathering gathering) {
gatheringDao.save(gathering);
}
/** * 删除 * * @param id */
// 删除数据库数据后需要删除redis中的缓存
@CacheEvict(value = "gathering", key = "#id")
public void deleteById(String id) {
gatheringDao.deleteById(id);
}