Caching made easy with CDI and Infinispan

When CDI and Inifispan meet you’ve got the chance to improve your code a lot. Let’s combine both to make all of your CDI beans @Cacheable.

Caching of values usually goes this way:

public String getSomething(String input) {
    String result = cache.contains(input);
    
	if(result == null) {
        result = getValueFromDatabase(input);
        cache.put(input, result);
    }
	
    return result;    
}

This pattern repeats for every value which is cached/retrieved. Methods like the one above contain repetitive conditionals and value retrievals. Using the caching interceptor pattern eliminates the need for repetition. Business methods will be reduced back to their essence and caching becomes an aspect.

@Cacheable
public String getSomething(@CacheKey String input) {
    return getValueFromDatabase(input);
}

How to:

  1. You need CDI (and Infinispan if you re-use the code without altering it)
  2. Grab the code from the Gist and put it into your project
  3. Annotate the methods you want to use the caching
  4. Enable the caching interceptor in your beans.xml
    <beans xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_0.xsd">
        <interceptors>
            <class>...CachingInterceptor</class>
        </interceptors>
    </beans>
  5. Build yourself a clear operation to manually evict the cache, you’ll need it.

Gist

You may also enjoy…