Search code examples
springehcache

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


Solution

  • 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);