Programmatic access to EhCache in Spring Boot

This guide assumes that you have already configured Ehcache, and is specifically concerned with programmatic addition and removal of elements.

Get a cache

@Autowired
private CacheManager cacheManager;

[...]

public Ehcache getCache(String name) {
    return cacheManager.getCache(name);
}

In the above example I have “wired in” the cache manager and called the getCache() method on it. This takes a String which is the name of the cache you wish to retrieve.

Populate a cache

private void updateCache() {
    getCache("example").put(new Element(entity.getName(), entity));
}

Once we have retrieved the cache, we can call put() on it. This method takes the type Element which encapsulates the key and value to be stored in the cache. The key can consist of one or more values that will uniquely identify the element in the specified cache.

Remove an element from a cache

public void remove(String name, Collection<Object> key) {
    Ehcache cache = getCache(name);

    if (cache.isKeyInCache(key)) {
        cache.remove(key);
    }
}

To remove an element from a cache we first need to built the key. This is a collection of type “Object” which will contain one or more values that will uniquely identify the element. First we will check that the key exists in the cache. If it does, we can call the remove method on the cache. This method takes the key as an argument.

private void removeFromCache(ApplicationHealth health) {
    remove("health", Arrays.asList(health.getName()));
}

19