【发布时间】:2020-04-24 11:59:28
【问题描述】:
我正在尝试在 Spring Boot RESTful 服务中实现 Spring 缓存。这是 getAllBlogs() 和 getBlogById() 方法的缓存代码。
@Cacheable(value="allblogcache")
@Override
public List<Blog> getAllBlogs() {
System.out.println("******* "+ blogRepository.findAll().toString());
return (List<Blog>) blogRepository.findAll();
}
@Cacheable(value="blogcache", key = "#blogId")
@Override
public Blog getBlogById(int blogId) {
Blog retrievedBlog = null;
retrievedBlog = blogRepository.findById(blogId).get();
return retrievedBlog;
}
在 saveBlog 方法中,我想清除缓存并使用了以下代码。
@Caching(evict = {
@CacheEvict(value="allblogcache"),
@CacheEvict(value="blogcache", key = "#blog.blogId")
})
@Override
public Blog saveBlog(Blog blog) {
return blogRepository.save(blog);
}
在运行时,我使用 Postman 执行了以下操作:
- 保存了两个博客。两个博客都被保存到数据库中。
- 调用获取所有博客。两个保存的博客都被返回。
- 保存了一个新博客。在这里,我假设缓存已被驱逐。
- 我调用了获取所有博客。但是,只有两个博客被返回。这 表示博客是从旧缓存中返回的。它没有被驱逐 调用第三次保存。
github repo 位于https://github.com/ximanta/spring-cache
【问题讨论】: