随后,再建立一个拦截器MethodCacheAfterAdvice,作用是在用户进行create/update/delete操作时来刷新、remove相关cache内容,这个拦截器需要实现AfterRetruningAdvice接口,将会在所拦截的方法执行后执行在afterReturning(object arg0,Method arg1,Object[] arg2,object arg3)方法中所预定的操作
- public class MethodCacheAfterAdvice implements AfterReturningAdvice, InitializingBean
- {
- private static final Log logger = LogFactory.getLog(MethodCacheAfterAdvice.class);
- private Cache cache;
- Page 15 of 26
- public void setCache(Cache cache) {
- this.cache = cache;
- }
- public MethodCacheAfterAdvice() {
- super();
- }
- public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws
- Throwable {
- String className = arg3.getClass().getName();
- List list = cache.getKeys();
- for(int i = 0;i<list.size();i++){
- String cacheKey = String.valueOf(list.get(i));
- if(cacheKey.startsWith(className)){
- cache.remove(cacheKey);
- logger.debug("remove cache " + cacheKey);
- }
- }
- }
- public void afterPropertiesSet() throws Exception {
- Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it.");
- }
- }
接着就是配置encache的属性,如最大缓存数量、cache刷新的时间等等。
- <ehcache>
- <diskStore path="c:\\myapp\\cache"/>
- <defaultCache
- maxElementsInMemory="1000"
- eternal="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- overflowToDisk="true"
- />
- <cache name="DEFAULT_CACHE"
- maxElementsInMemory="10000"
- eternal="false"
- timeToIdleSeconds="300000"
- timeToLiveSeconds="600000"
- overflowToDisk="true"
- />
- </ehcache>
然后再将Cache和两个拦截器配置到Spring的配置文件cache.xml中即可,需要创建两个“切入点”,分别用于拦截不同方法名的方法。在配置application.xml并且导入cache.xml。这样一个简单的Spring+Encache框架就搭建完成。
由于时间关系就介绍到这里,以后有机会还会介绍Ehcache在分布式集群系统中的使用,谢谢大家。
