ehcache 与spring相结合超时自动刷新缓存的框架搭建

我们在做J2EE工程中经常会碰到一些常量或者是一些不太用的数据。

 

这部分数据我们希望是把它放到一个共同的地方,然后大家都能去调用,而不用频繁调用数据库以提高web访问的效率。

 

这样的东西就是缓存(cache),对于缓存的正确理解是一块不太变动的数据,但是这块数据偶尔或者周期新会被变动的,如:

 

地区,分公司,省市。。。。。。

 

当系统一开始运行时,我们可以把一批静态的数据放入cache,当数据变化时,我们要从数据库把最新的数据拿出来刷新这块cache

 

我们以前的作法是做一个static 的静态变量,把这样的数据放进去,然后用一个schedule job定期去刷新它,然后在用户访问时先找内存,如果内存里没有找到再找数据库,找到数据库中的数据后把新的数据放入 cache

 

这带来了比较繁琐的编码工作,伴随而来的代码维护和性能问题也是很受影响的。

 

因此在此我们引入了ehcache组件。

 

目前市面上比较流行的是oscacheehcache,本人这一阵对两种cache各作了一些POC,作了一些比较,包括在cluster环境下的试用,觉得在效率和性能上两者差不多。

 

但是在配置和功能上ehcache明显有优势。

 

特别是spring2后续版本引入了对ehcache的集成后,更是使得编程者在利用缓存的问题上大为受益,我写这篇文章的目的就是为了使用SPRING AOP的功能,把调用维护ehcacheAPI函数封装入框架中,使得ehcache的维护对于开发人员来说保持透明。

  

Ehcache的配置件(ehcache.xml):

 

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="/tmp"/>

      

    <defaultCache

            maxElementsInMemory="500"

            eternal="false"

            timeToIdleSeconds="0"

            timeToLiveSeconds="60"

            overflowToDisk="false"

            maxElementsOnDisk="0"

            diskPersistent="false"

            diskExpiryThreadIntervalSeconds="0"

            memoryStoreEvictionPolicy="LRU"

            />

    <cache name="countryCache"

            maxElementsInMemory="10000"

            eternal="false"

            timeToIdleSeconds="0"

            timeToLiveSeconds="60"

            overflowToDisk="false"

            maxElementsOnDisk="0"

            diskPersistent="false"

            diskExpiryThreadIntervalSeconds="0"

            memoryStoreEvictionPolicy="LRU">

    </cache>

   

</ehcache>

 

1.必须要有的属性:

 

name: cache的名字,用来识别不同的cache,必须惟一。

 

maxElementsInMemory: 内存管理的缓存元素数量最大限值。

 

maxElementsOnDisk: 硬盘管理的缓存元素数量最大限值。默认值为0,就是没有限制。

 

eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。

 

overflowToDisk: 设定是否在内存填满的时候把数据转到磁盘上。

 

2.下面是一些可选属性:

 

timeToIdleSeconds 设定元素在过期前空闲状态的时间,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无限长时间。

 

timeToLiveSeconds: 设定元素从创建到过期的时间。其他与timeToIdleSeconds类似。

 

diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安全小型应用,宜设为true)

 

diskExpiryThreadIntervalSeconds: 访问磁盘线程活动时间。

 

diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有自己的缓冲区。

 

memoryStoreEvictionPolicy: 元素逐出缓存规则。共有三种,Recently Used (LRU)最近最少使用,为默认。 First In First Out (FIFO),先进先出。Less Frequently Used(specified as LFU)最少使用。

 

根据描述,上面我们设置了一个60秒过期不使用磁盘持久策略的缓存。

 

下面来看与spring的结合,我作一了个ehcacheBean.xml文件:

 

<?xml version="1.0" encoding="UTF-8"?>  

 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

                <bean id="defaultCacheManager"

                                class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">

                                <property name="configLocation">

                                                <value>classpath:ehcache.xml</value>

                                </property>

                </bean>

 

 

                <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">

                                <property name="cacheManager">

                                                <ref local="defaultCacheManager" />

                                </property>

                                <property name="cacheName">

                                                <value>countryCache</value>

                                </property>

                </bean>

 

                <bean id="methodCacheInterceptor" class="com.testcompany.framework.ehcache.MethodCacheInterceptor">

                                <property name="cache">

                                                <ref local="ehCache" />

                                </property>

                </bean>

 

             <bean id="methodCacheAfterAdvice" class="com.testcompany.framework.ehcache.MethodCacheAfterAdvice">

                                <property name="cache">

                                                <ref local="ehCache" />

                                </property>

                </bean>

 

                <bean id="methodCachePointCut"

                                class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">

                                <property name="advice">

                                                <ref local="methodCacheInterceptor" />

                                </property>

                                <property name="patterns">

                                                <list>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheFind*.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheGet*.*</value>

                                                </list>

                                </property>

                </bean>

                <bean id="methodCachePointCutAdvice"

                                class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">

                                <property name="advice">

                                                <ref local="methodCacheAfterAdvice" />

                                </property>

                                <property name="patterns">

                                                <list>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheCreate.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheUpdate.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheDelete.*</value>

                                                </list>

                                </property>

                </bean>

</beans> 

 

在此我定义了两个拦截器,一个叫MethodCacheInterceptor一个叫MethodCacheAfterAdvice

 

这两个拦截器的作用就是提供:

 

1.       用户调用ehcache时,自动先找ehcache中的对象,如果找不到再调用相关的service方法(如调用DB中的SQL来查询数据)。

 

它对以以下表达式的类方法作intercept:

 

                                                 <list>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheFind*.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheGet*.*</value>

                                                </list>

 

2.       为用户提供了一套管理ehcacheAPI函数,使得用户不用去写ehcacheapi函数来对ehcacheCRUD的操作

 

它对以以下表达式的类方法作after advice:

 

                                                <list>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheCreate.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheUpdate.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheDelete.*</value>

                                                </list>

 

我们一起来看这两个类的具体实现吧。

 

MethodCacheInterceptor.class

 

public class MethodCacheInterceptor implements MethodInterceptor,

                                InitializingBean {

                private final Log logger = LogFactory.getLog(getClass());

 

                private Cache cache;

 

                public void setCache(Cache cache) {

                                this.cache = cache;

                }

 

                public MethodCacheInterceptor() {

                                super();

                }

 

                @Override

                public Object invoke(MethodInvocation invocation) throws Throwable {

                                String targetName = invocation.getThis().getClass().getName();

                                String methodName = invocation.getMethod().getName();

                                Object[] arguments = invocation.getArguments();

                                Object result;

 

                                logger.info("Find object from cache is " + cache.getName());

 

                                String cacheKey = getCacheKey(targetName, methodName, arguments);

                                Element element = cache.get(cacheKey);

 

                                if (element == null) {

                                                logger

                                                                                .info("Can't find result in Cache , Get method result and create cache........!");

                                                result = invocation.proceed();

                                                element = new Element(cacheKey, (Serializable) result);

                                                cache.put(element);

                                }else{

                                                logger

                                                .info("Find result in Cache , Get method result and create cache........!");

                                }

                                return element.getValue();

                }

 

                private String getCacheKey(String targetName, String methodName,

                                                Object[] arguments) {

                                StringBuffer sb = new StringBuffer();

                                sb.append(targetName).append(".").append(methodName);

                                if ((arguments != null) && (arguments.length != 0)) {

                                                for (int i = 0; i < arguments.length; i++) {

                                                                sb.append(".").append(arguments[i]);

                                                }

                                }

                                return sb.toString();

                }

 

                public void afterPropertiesSet() throws Exception {

                                if (cache == null) {

                                                logger.error("Need a cache. Please use setCache(Cache) create it.");

                                }

                }

 

}

 

MethodCacheAfterAdvice

 

public class MethodCacheAfterAdvice implements AfterReturningAdvice,

                                InitializingBean {

 

                private final Log logger = LogFactory.getLog(getClass());

 

                private Cache cache;

 

                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 {

                                if (cache == null) {

                                                logger.error("Need a cache. Please use setCache(Cache) create it.");

                                }

                }

 

}

我们一起来看EHCacheComponent类的具体实现吧:

 

@Component

public class EHCacheComponent {

               

                protected final Log logger = LogFactory.getLog(getClass());

               

                @Resource

                private ICommonService commonService;

               

                public List<CountryDBO> cacheFindCountry()throws Exception{

                                return commonService.getCountriesForMake();

                }

}

 

该类中的方法cacheFindCountry()就是一个从缓存里找country信息的类。

因此,public List<CountryDBO> cacheFindCountry()是被cache的,每次调用时该方法都会被MethodCacheInterceptor拦截住,然后先去找cache,如果当在缓存里找到cacheFindCountry的对象后会直接返回一个list,如果没有,它会去调用servicegetCountriesForMake()方法。

 

现在来看我们原来的action的写法与更改成ehcache方式的写法。

 

               //List<CountryDBO> countries = commonService.getCountriesForMake();         /*原来在action中的调用*/

               

                List<CountryDBO> countries =cache.cacheFindCountry();                                         /*现在的调用*/

 

这时,用法登录主界面,查询国别信息,后台log日志报出:

 

2011-02-18 12:25:49  INFO MethodCacheInterceptor:33 - Find object from cache is countryCache

2011-02-18 12:25:49  INFO MethodCacheInterceptor:40 - Can't find result in Cache , Get method result and create cache........!

2011-02-18 12:25:49  INFO CommonDAOImpl:30 - >>>>>>>>>>>>>>>>>get counter for make from db

 

再次作国别信息的查询,后台log日志报出:

 

2011-02-18 11:58:26  INFO MethodCacheInterceptor:33 - Find object from cache is countryCache

2011-02-18 11:58:26  INFO MethodCacheInterceptor:46 - Find result in Cache , Get method result and create cache........!

 

 

此处的2011-02-18 12:25:49  INFO CommonDAOImpl:30 - >>>>>>>>>>>>>>>>>get counter for make from db语句是我故意放在调用数据库的dao方法开头的。

 

使得每次getCountriesForMakeservice方法去调用这个daodao. getCountriesForMake()方法时被log日志打印一下。

 

因此在60秒内我们做两次这样的国别信息查询,第一次是走dao,第二次没走DAO,但是国别信息也被查询出来了,大功告成。

 

最后:

 

ehcache.xml文件中的配置中的两个值的更改需要根据实际情况:

            timeToIdleSeconds="0"

            timeToLiveSeconds="60"

 

比如说如果你的国别过1个月会被客服人员更新一次,那可以把这个timeToLiveSeconds时间设置为一个月的秒。

timeToIdleSeconds这个值代表这个值如果在timeToLiveSeconds期内没人动,就会一直闲置着,而不会销毁。

上一篇:Picasso 加载图片到RelativeLayout之解决方案


下一篇:设计模式总结篇系列:命令模式(Command)