As you may know, Spring 3.1 provides method annotations to be able
cache the result of method calls.
http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html
Ehcache is supported builtin and I have written the following code to
provide support for Hazelcast. Sharing it incase someone else may
need the same thing.
import java.util.Collection;
import java.util.LinkedHashSet;
import org.springframework.cache.Cache;
import org.springframework.cache.support.AbstractCacheManager;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
public class HazelcastCacheManager extends AbstractCacheManager {
private HazelcastInstance hazelcastInstance;
private String mapName;
public HazelcastCacheManager(HazelcastInstance
hazelcastInstance,String mapName) {
this.hazelcastInstance = hazelcastInstance;
this.mapName = mapName;
}
@Override
protected Collection<Cache> loadCaches() {
Collection<Cache> caches = new LinkedHashSet<Cache>(1);
IMap<Object, Object> map = hazelcastInstance.getMap(mapName);
caches.add(new HazelcastCache(mapName,map));
return caches;
}
}
And the cache class
import java.util.Map;
import org.springframework.cache.Cache;
import org.springframework.cache.support.ValueWrapperImpl;
public class HazelcastCache implements Cache {
private final Map<Object, Object> cacheMap;
private final String name;
public HazelcastCache(String name, Map<Object, Object> cacheMap) {
this.name = name;
this.cacheMap = cacheMap;
}
@Override
public void clear() {
cacheMap.clear();
}
@Override
public void evict(Object key) {
if (key != null) {
cacheMap.remove(key);
}
}
@Override
public ValueWrapper get(Object key) {
if (key == null) {
return null;
}
Object value = cacheMap.get(key);
return value == null ? null : new ValueWrapperImpl(value);
}
@Override
public String getName() {
return name;
}
@Override
public Object getNativeCache() {
return cacheMap;
}
@Override
public void put(Object key, Object value) {
if ((key != null) && (value != null)) {
cacheMap.put(key, value);
}
}
}
Spring configuration
<cache:annotation-driven cache-manager="cacheManager" />
<bean id="cacheManager" class="com.prime.HazelcastCacheManager">
<constructor-arg ref="hazelinstance" />
<constructor-arg value="springcache" />
</bean>
and you also need to define a map for spring cache
<hz:map name="springcache" ....>
</hz:map>