现在的位置: 首页 > 综合 > 正文

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

2013年01月01日 ⁄ 综合 ⁄ 共 11934字 ⁄ 字号 评论关闭

我们在做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中的调用*/

抱歉!评论已关闭.