Reputation: 1306
I'm trying to implement Spring caching in a Spring Boot RESTful service. This is the caching code for the getAllBlogs() and getBlogById() methods.
@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;
}
In the saveBlog method I want to evict the cache and have used the following code.
@Caching(evict = {
@CacheEvict(value="allblogcache"),
@CacheEvict(value="blogcache", key = "#blog.blogId")
})
@Override
public Blog saveBlog(Blog blog) {
return blogRepository.save(blog);
}
On running, I did the following using Postman:
The github repo is at https://github.com/ximanta/spring-cache
Upvotes: 1
Views: 1959
Reputation: 6391
You need to add allEntries = true
attribute if you're evicting caches without specifying a key (see docs).
In your case, it would be @CacheEvict(value="allblogcache", allEntries = true)
P.S. tested it and managed to make it work. PR: https://github.com/ximanta/spring-cache/pull/1
Upvotes: 1
Reputation: 18235
It throw exception because you use wrong key expression:
@Caching(evict = {
@CacheEvict(value="allblogcache"),
@CacheEvict(value="blogcache", key = "#blogId")
~~~~~~~~~~ => Refer to parameter blogId but not found
})
public Blog saveBlog(Blog blog)
The correct expression is:
@Caching(evict = {
@CacheEvict(value="allblogcache"),
@CacheEvict(value="blogcache", key = "#blog.id") // Assume that the property for blog ID is "id"
})
public Blog saveBlog(Blog blog)
Upvotes: 0