0

Can someone tell me what is the problem with below implementation. I'm trying to delete the entire cache, secondly, I then want to pre-populate/prime the cache. However, what I've below is only deleting both caches, but not pre-populating/priming the cache, when the two methods are executed. Any idea?

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

@Cacheable(cacheNames = "cacheOne")
List<User> cacheOne() throws Exception {...}

@Cacheable(cacheNames = "cacheOne")
List<Book> cacheTwo() throws Exception {...}

@Caching (
        evict = {
                @CacheEvict(cacheNames = "cacheOne", allEntries = true),
                @CacheEvict(cacheNames = "CacheTwo", allEntries = true)
        }
)
void clearAndReloadEntireCache() throws Exception
{
    // Trying to reload cacheOne and cacheTwo inside this method
    // Is this even possible? if not what is the correct approach?
    cacheOne();
    cacheTwo(); 
}

I've spring boot application (v1.4.0), more importantly, utilizing the following dependencies:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
     <groupId>org.ehcache</groupId>
     <artifactId>ehcache</artifactId>
     <version>3.3.0</version>
 </dependency>
 <dependency>
     <groupId>javax.cache</groupId>
     <artifactId>cache-api</artifactId>
     <version>1.0.0</version>
 </dependency>
Simple-Solution
  • 4,209
  • 12
  • 47
  • 66

1 Answers1

1

If you call the clearAndReloadEntireCache() method, only this method will be processed by the caching interceptor. Calling other methods of the same object: cacheOne() and cacheTwo() will not cause cache interception at runtime, although both of them are annotated with @Cacheable.

You could achieve desired functionality by reloading cacheOne and cacheTwo with two method calls shown below:

@Caching(evict = {@CacheEvict(cacheNames = "cacheOne", allEntries = true, beforeInvocation = true)},
        cacheable = {@Cacheable(cacheNames = "cacheOne")})
public List<User> cleanAndReloadCacheOne() {
    return cacheOne();
}

@Caching(evict = {@CacheEvict(cacheNames = "cacheTwo", allEntries = true, beforeInvocation = true)},
        cacheable = {@Cacheable(cacheNames = "cacheTwo")})
public List<Book> cleanAndReloadCacheTwo() {
    return cacheTwo();
}  
Igor
  • 1,406
  • 2
  • 23
  • 45