Spring AOP+ehCache简单缓存系统解决方案

需要使用Spring来实现一个Cache简单的解决方案,具体需求如下:使用任意一个现有开源Cache Framework,要求可以Cache系统中Service或则DAO层的get/find等方法返回结果,如果数据更新(使用Create /update/delete方法),则刷新cache中相应的内容。

根据需求,计划使用Spring AOP + ehCache来实现这个功能,采用ehCache原因之一是Spring提供了ehCache的支持,至于为何仅仅支持ehCache而不支持 osCache和JBossCache无从得知(Hibernate???),但毕竟Spring提供了支持,可以减少一部分工作量:)。二是后来实现了 OSCache和JBoss Cache的方式后,经过简单测试发现几个Cache在效率上没有太大的区别(不考虑集群),决定采用ehCahce。

AOP 嘛,少不了拦截器,先创建一个实现了MethodInterceptor接口的拦截器,用来拦截Service/DAO的方法调用,拦截到方法后,搜索该方法的结果在cache中是否存在,如果存在,返回cache中的缓存结果,如果不存在,返回查询数据库的结果,并将结果缓存到cache中。

MethodCacheInterceptor.java
Java代码
package com.co.cache.ehcache;

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean
{
private static final Log logger = LogFactory.getLog(MethodCacheInterceptor.class);

private Cache cache;

public void setCache(Cache cache) {
this.cache = cache;
}

public MethodCacheInterceptor() {
super();
}

/**
* 拦截Service/DAO的方法,并查找该结果是否存在,如果存在就返回cache中的值,
* 否则,返回数据库查询结果,并将查询结果放入cache
*/
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.debug("Find object from cache is " + cache.getName());

String cacheKey = getCacheKey(targetName, methodName, arguments);
Element element = cache.get(cacheKey);

if (element == null) {
logger.debug("Hold up method , Get method result and create cache........!");
result = invocation.proceed();
element = new Element(cacheKey, (Serializable) result);
cache.put(element);
}
return element.getValue();
}

/**
* 获得cache key的方法,cache key是Cache中一个Element的唯一标识
* cache key包括 包名+类名+方法名,如com.co.cache.service.UserServiceImpl.getAllUser
*/
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();
}

/**
* implement InitializingBean,检查cache是否为空
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it.");
}

}


上面的代码中可以看到,在方法public Object invoke(MethodInvocation invocation) 中,完成了搜索Cache/新建cache的功能。
Java代码
Element element = cache.get(cacheKey);

这句代码的作用是获取cache中的element,如果cacheKey所对应的element不存在,将会返回一个null值

Java代码
result = invocation.proceed();

这句代码的作用是获取所拦截方法的返回值,详细请查阅AOP相关文档。

随后,再建立一个拦截器MethodCacheAfterAdvice,作用是在用户进行create/update/delete操作时来刷新 /remove相关cache内容,这个拦截器实现了AfterReturningAdvice接口,将会在所拦截的方法执行后执行在public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3)方法中所预定的操作
Java代码
package com.co.cache.ehcache;

import java.lang.reflect.Method;
import java.util.List;

import net.sf.ehcache.Cache;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class MethodCacheAfterAdvice implements AfterReturningAdvice, InitializingBean
{
private static final Log logger = LogFactory.getLog(MethodCacheAfterAdvice.class);

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 {
Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it.");
}

}

上面的代码很简单,实现了afterReturning方法实现自AfterReturningAdvice接口,方法中所定义的内容将会在目标方法执行后执行,在该方法中
Java代码
String className = arg3.getClass().getName();
的作用是获取目标class的全名,如:com.co.cache.test.TestServiceImpl,然后循环cache的key list,remove cache中所有和该class相关的element。

随后,开始配置ehCache的属性,ehCache需要一个xml文件来设置ehCache相关的一些属性,如最大缓存数量、cache刷新的时间等等.
ehcache.xml
Java代码
<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>

配置每一项的详细作用不再详细解释,有兴趣的请google下 ,这里需要注意一点defaultCache标签定义了一个默认的Cache,这个Cache是不能删除的,否则会抛出No default cache is configured异常。另外,由于使用拦截器来刷新Cache内容,因此在定义cache生命周期时可以定义较大的数值,timeToIdleSeconds="300000" timeToLiveSeconds="600000",好像还不够大?

然后,在将Cache和两个拦截器配置到Spring,这里没有使用2.0里面AOP的标签。
cacheContext.xml
Java代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<!-- 引用ehCache的配置 -->
<bean id="defaultCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>

<!-- 定义ehCache的工厂,并设置所使用的Cache name -->
<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="defaultCacheManager"/>
</property>
<property name="cacheName">
<value>DEFAULT_CACHE</value>
</property>
</bean>

<!-- find/create cache拦截器 -->
<bean id="methodCacheProxy" class="com.lto.tags.core.monitor.MethodCacheProxy">
<property name="cache">
<ref local="ehCache" />
</property>
</bean>
<!-- flush cache拦截器 -->
<bean id="methodCacheAfterAdvice" class="com.lto.tags.core.monitor.MethodCacheAfterAdvice">
<property name="cache">
<ref local="ehCache" />
</property>
</bean>



<!-- 事件日志总线 -->
<bean id="eventLogProxy" class="com.lto.tags.core.monitor.EventLogProxy" />

<!-- 事务通知 -->
<tx:advice id ="txAdvice" transaction-manager ="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="is*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="load*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<tx:method name ="*" propagation="REQUIRES_NEW" rollback-for="Exception" />
</tx:attributes>
</tx:advice>

<!-- 事务管理 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- 日志/异常/事务/二级缓存切入点 -->
<aop:config>

<!-- 事务切入点 -->
<aop:pointcut id="allManagerMethod"
expression="execution(* com.lto.tags.dom.service.impl.*.*(..))||execution(* com.lto.tags.core.BaseService.*(..))" />
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice" order="3"/>

<!-- 缓存切入点 -->
<aop:advisor pointcut="execution(* com.lto.tags.dao.impl.*.find*(..))||execution(* com.lto.tags.dao.impl.*.get*(..))||execution(* com.lto.tags.dao.impl.*.is*(..))||execution(* com.lto.tags.dao.impl.*.query*(..))||execution(* com.lto.tags.dao.impl.*.list*(..))||execution(* com.lto.tags.core.dao.BaseDao.find*(..))" advice-ref="methodCacheProxy" order="1"/>
<aop:advisor pointcut="execution(* com.lto.tags.dao.impl.*.save*(..))||execution(* com.lto.tags.dao.impl.*.delete*(..))||execution(* com.lto.tags.dao.impl.*.update*(..))||execution(* com.lto.tags.dao.impl.*.marge*(..))||execution(* com.lto.tags.core.dao.BaseDao.save*(..))||execution(* com.lto.tags.core.dao.BaseDao.delete*(..))||execution(* com.lto.tags.core.dao.BaseDao.update*(..))||execution(* com.lto.tags.core.dao.BaseDao.marge*(..))" advice-ref="methodCacheAfterAdvice" order="2"/>

<!-- 事件日志/异常切入点 -->
<!--<aop:aspect id="runProxy" ref="eventLogProxy" order="4">
<aop:around method="ActionAround" pointcut="execution(* com.lto.tags.*.*.*.*(..)) and @annotation(methodInfo)"/>
</aop:aspect>
-->

</aop:config>

</beans>

上面的advisor分别用于拦截不同方法名的方法,可以根据需要任意增加所需要拦截方法的名称。
需要注意的是
Java代码
<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="defaultCacheManager"/>
</property>
<property name="cacheName">
<value>DEFAULT_CACHE</value>
</property>
</bean>

如果cacheName属性内设置的name在ehCache.xml中无法找到,那么将使用默认的cache(defaultCache标签定义).

网上也有不少类似的例子,但是很多都不是很完备,自己参考了一些例子的代码,其实在spring-modules中也提供了对几种cache的支持,ehCache,OSCache,JBossCache这些,看了一下,基本上都是采用类似的方式,只不过封装的更完善一些,主要思路也还是 Spring的AOP,有兴趣的可以研究一下。
补充spring的资源资源配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config />
<context:component-scan base-package="com.lto.tags" />


<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>

<!-- 多线程任务处理器 -->
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="1" /> <!-- 核心线程数 -->
<property name="keepAliveSeconds" value="200" /> <!-- 线程池维护线程所允许的空闲时间,默认为60s -->
<property name="maxPoolSize" value="1" /> <!-- 最大线程数 -->
<property name="queueCapacity" value="25" /> <!-- 队列最大长度 -->
<!-- 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者 -->
<property name="rejectedExecutionHandler">
<!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->
<!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->
<!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
<!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
<bean
class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>

<!-- 配置 dataSource-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!-- MySQL DataBase -->
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>

<!-- Oracle DataBase -->
<!--
<property name="driverClassName" value="${g4.jdbc.driverClassName}"/>
<property name="url" value="${g4.jdbc.url}"/>
<property name="username" value="${g4.jdbc.username}"/>
<property name="password" value="${g4.jdbc.password}"/>
-->
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
<property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
<property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"/>
<property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}"/>
<property name="testConnectionOnCheckin" value="${jdbc.testConnectionOnCheckin}"/>
<property name="automaticTestTable" value="${jdbc.automaticTestTable}"/>
<property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"/>
<property name="checkoutTimeout" value="${jdbc.checkoutTimeout}"/>


</bean>

<!-- 配置 jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>

<!-- 配置Ibatis sqlmapClientFactory -->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocations">
<list>
<value>classpath:ibatis.sqlmap.xml</value>
</list>
</property>
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 配置 sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingLocations">
<list>
<value>classpath*:com/lto/tags/model/po/hibernatemaps/*.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="connection.useUnicode">true</prop>
<prop key="connection.characterEncoding">utf-8</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
<prop key="hibernate.jdbc.fetch_size">20</prop>
<prop key="show_sql">false</prop>
[color=red]<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="net.sf.ehcache.configurationResourceName">classpath:ehcache.xml</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>[/color]
</props>
</property>
</bean>

<!-- 配置 hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值