user2693135
user2693135

Reputation: 1306

Cache Evict issue with @Cacheable parameterless method

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:

  1. Saved two blogs. Both blogs are getting saved to the database.
  2. called get All blogs. Both the saved blogs are returned.
  3. Saved a new blog. Here I assume the cache has been evicted.
  4. I called get All blogs. However, only two blogs are getting returned. This means the blogs are returned from the old cache. It didn't get evicted by the call to the third save.

The github repo is at https://github.com/ximanta/spring-cache

Upvotes: 1

Views: 1959

Answers (2)

amseager
amseager

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

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

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

Related Questions