springboot cache的使用
1.开始使用前需要导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2.然后在启动类注解@EnableCaching开启缓存
@SpringBootApplication
@EnableCaching //开启缓存
public class DemoApplication{
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3.缓存@Cacheable
实现效果第一次访问查询数据库,第二次刷新就不会再查询数据库了
@Cacheable
注解会先查询是否已经有缓存,有会使用缓存,没有则会执行方法并缓存。
//有参数就加上+#p0 没参数就不要加
@Cacheable(value = "emp" ,key = "targetClass + methodName +#p0")
public List<NewJob> queryAll(User uid) {
return newJobDao.findAllByUid(uid);
}
@GetMapping("/file/front/all")
@Cacheable(value = "files" ,key = "targetClass + methodName")
public Result frontAll(){
return Result.success(fileMapper.selectList(null));
}
@Cacheable(value = "files" ,key = "'frontAll'")
此处的value
是必需的,它指定了你的缓存存放在哪块命名空间。
//注意
使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。 如:
@Cacheable(value="users", key="#id")
@Cacheable(value="users", key="#p0")
缓存的一个问题
数据删除或更新 缓存没有及时的改变
解决方法
//更新后清空缓存
@CachePut(value = "files", key = "'frontAll'") //注意key要和缓存的key一样
@PostMapping("/update")
public Result updata(@RequestBody Files files) {
return Result.success(fileMapper.selectList(null));
}
}
//清除一条缓存,key为要清空的数据
@CacheEvict(value="emp",key="'frontAll'")
@DeleteMapping("/{id}")
public void delect(@PathVariable int id) {
newJobDao.deleteAllById(id);
}
//方法调用后清空所有缓存
@CacheEvict(value="accountCache",allEntries=true)
public void delectAll() {
newJobDao.deleteAll();
}
//方法调用前清空所有缓存
@CacheEvict(value="accountCache",beforeInvocation=true)
public void delectAll() {
newJobDao.deleteAll();
}