Saturday, November 7, 2015

Java/Spring Caching

File it under "another thing I need to do a lot"... Some kind of caching of java objects.

Turns out there is a neat cache library from google called Guava that's very easy to inject into Spring and easy to configure and access.

The Spring beans look like this:


<bean id="cacheBuilderSpec"
  class="com.google.common.cache.CacheBuilderSpec"
  factory-method="parse"
  c:cacheBuilderSpecification="${cacheSpecification}" />

<bean id="cacheBuilderFromSpec"
  class="com.google.common.cache.CacheBuilder"
  factory-method="from"
  c:spec-ref="cacheBuilderSpec" />

<bean id="cache"
  factory-bean="cacheBuilderFromSpec"
  factory-method="build" />



And where the injected $cacheSpecification looks like this:

cacheSpecification=expireAfterAccess=12h,maximumSize=100

Using it in my code then becomes a simple matter of injecting the 'cache' bean into whatever class I'm using and then accessing it with these kinds of code:

cache.getIfPresent(object)
cache.invalidate(object)