Devoxx – Improve the performance of your Spring app

Leave a comment
Dev

This talk by Costin Leau was about the new caching features in Spring 3.1.

After going over some problems you can face when caching (stale data, thrashing, distributed caches) and different caching patterns he introduced the declarative caching of Spring 3.1.

It uses AOP and can be declared on methods by adding the @Cacheable annotation. This annotation caches a method’s return value using it’s parameters as the key although this can be customised.

Eg:

@Cacheable
public Owner loadOwner(int id);

@Cacheable("owners")
public Owner loadOwner(int id);

// Using Spring expression language
@Cacheable(key="tag.name")
public Owner loadOwner(Tag tag, Date created);

@Cacheable(key="T(someType).hash(name)")
public Owner loadOwner(String name);

// Only cache on condition
@Cacheable(condition="name < 10")
public Owner loadOwner(String name, Date created);

The @CacheEvict annotation invalidates the cache:

@CacheEvict
public void deleteOwner(int id);

@CacheEvict("owners", key="id")
public void deleteOwner(int id, boolean saveCopy);

@CacheEvict(name="owners", allEntries=true)
public void batchUpdate()

You can also use your own stereotype annotations. Instead of spreading @Cacheable everywhere:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Cacheable("results")
public @interface SlowService {

}

@SlowService
public Source search(String tag) {...}

Spring is not a cache provider itself. You plug in your own cache provider (ehcache, JBoss Cache, etc).

Leave a Reply

Your email address will not be published. Required fields are marked *