Thursday, 19 November 2015

How to implement Spring Cache?

To use simple Spring Cache based on Map logic we need to do two things:

1. Add cacheManager in our application context:

<cache:annotation-driven cache-manager="cacheManager"/>

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="sourceSystemsCache/>
// add more caches
</set>
</property>
</bean>

2. In bean add annotation above method:

@Cacheable("cacheName") // in our case sourceSystemsCache
public int doSomething(int i) {..}

Note: besides cache name, you can indicate which values not to cache (usually using spring spel) etc.

Also useful is to reset cache which can be done using fake method or method that deletes date from db and we in out case delete it from our cache.

@CacheEvict(value = "cacheName", beforeInvocation = true)
public void deleteCacheName() { //do nothing }

@CacheEvict(value = "userCache", beforeInvocation = true)
public void deleteUserName(User user) { dao.delete(user); }

I had a task to reset all cache using rest, so I wrote service where I have autowired SimpleCacheManager and took its all cacheNames it contained and just cleared them:

public class CacheServiceImpl implements CacheService {

@Autowired
private SimpleCacheManager manager;

@Override
public boolean resetCache() {
    for (String cacheName : manager.getCaheNames()) {
         manager.getCache(cacheName).clear();
}
}

}

No comments:

Post a Comment