thandem
thandem

Reputation: 310

Evict Ehcache elements programmatically, using Spring

I'm new to Spring and Caching, and I would like your help.

I'm caching Link object by using Spring annotation

@CachePut(value=CACHE_NAME, key="{#root.targetClass, #link.getId()}")
public Link update(Link link) {...}

Now, I want to programmatically clear those links that have been cached, so I tried this.

Ehcache cache = cacheManager.getEhcache(CACHE_NAME);
for(Link link : links) {
   List key = Arrays.asList(new String[] {this.getClass().toString(), link.getId()});
   cache.remove(key.toString());
}

So, I've noticed that is not working. Do you know what SpEL's list ouput is? What key value need I expect in cache?

Thanks in advance, TD

Upvotes: 3

Views: 12627

Answers (2)

saran3h
saran3h

Reputation: 14022

@Component
@Slf4j
@AllArgsConstructor
public class CacheHelper {

    private CacheManager cacheManager;

    /**
     * Evicts all caches
     */
    public void evictAllCaches() {
        Collection<String> cacheNames = cacheManager.getCacheNames();
        cacheNames.stream().map(cacheManager::getCache)
                .filter(Objects::nonNull)
                .forEach(Cache::clear);
        log.debug("Caches evicted [{}]", cacheNames);
    }
}

I've made this little snippet to clear all the caches.

Upvotes: 1

Jose Luis Martin
Jose Luis Martin

Reputation: 10709

Creating the cache key is a internal operation of the framework. Seem better option to use the public API to evict.

For example

@CacheEvict(value=CACHE_NAME, key="{#root.targetClass, #link.getId()}")
public Link evict(Link link) {
   // nothing to do
}

However I suppose that the following code will work

List key = new ArrayList();
key.add(LinkService.class);
key.add(link.getId());
cache.evict(key);

Upvotes: 8

Related Questions