`

Spring 之 EHcache配置

阅读更多
http://blog.csdn.net/yangfanend/article/details/7661885

SpringCacheBeanAOPXML
需要使用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.");  
    }  
 

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

这句代码的作用是获取cache中的element,如果cacheKey所对应的element不存在,将会返回一个null值
Java代码
result = invocation.proceed(); 
[java] view plaincopy
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.");  
    }  
 

[java] view plaincopy
上面的代码很简单,实现了afterReturning方法实现自AfterReturningAdvice接口,方法中所定义的内容将会在目标方法执行后执行,在该方法中  
Java代码
String className = arg3.getClass().getName(); 
[java] view plaincopy
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> 
[java] view plaincopy
 
配置每一项的详细作用不再详细解释,有兴趣的请google下 ,这里需要注意一点defaultCache标签定义了一个默认的Cache,这个Cache是不能删除的,否则会抛出No default cache is configured异常。另外,由于使用拦截器来刷新Cache内容,因此在定义cache生命周期时可以定义较大的数值,timeToIdleSeconds="300000" timeToLiveSeconds="600000",好像还不够大?然后,在将Cache和两个拦截器配置到Spring,这里没有使用2.0里面AOP的标签。 cacheContext.xml
Java代码
[java] view plaincopy
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//<span class="hilite1" style="background-color:rgb(255,255,0)">SPRING</span>//DTD BEAN//EN" "http://www.springframework.org/dtd/<span class="hilite1" style="background-color:rgb(255,255,0)">spring</span>-beans.dtd"> 
<beans> 
    <!-- 引用<span class="hilite3" style="background-color:rgb(170,255,170)">ehCache</span>的配置 --> 
    <bean id="defaultCacheManager" class="org.springframework.cache.<span class="hilite3" style="background-color:rgb(170,255,170)">ehcache</span>.EhCacheManagerFactoryBean"> 
      <property name="configLocation"> 
        <value><span class="hilite3" style="background-color:rgb(170,255,170)">ehcache</span>.xml</value> 
      </property> 
    </bean> 
     
    <!-- 定义<span class="hilite3" style="background-color:rgb(170,255,170)">ehCache</span>的工厂,并设置所使用的Cache name --> 
    <bean id="<span class="hilite3" style="background-color:rgb(170,255,170)">ehCache</span>" class="org.springframework.cache.<span class="hilite3" style="background-color:rgb(170,255,170)">ehcache</span>.EhCacheFactoryBean"> 
      <property name="cacheManager"> 
        <ref local="defaultCacheManager"/> 
      </property> 
      <property name="cacheName"> 
          <value>DEFAULT_CACHE</value> 
      </property> 
    </bean> 
 
    <!-- find/create cache拦截器 --> 
    <bean id="methodCacheInterceptor" class="com.co.cache.<span class="hilite3" style="background-color:rgb(170,255,170)">ehcache</span>.MethodCacheInterceptor"> 
      <property name="cache"> 
        <ref local="<span class="hilite3" style="background-color:rgb(170,255,170)">ehCache</span>" /> 
      </property> 
    </bean> 
    <!-- flush cache拦截器 --> 
    <bean id="methodCacheAfterAdvice" class="com.co.cache.<span class="hilite3" style="background-color:rgb(170,255,170)">ehcache</span>.MethodCacheAfterAdvice"> 
      <property name="cache"> 
        <ref local="<span class="hilite3" style="background-color:rgb(170,255,170)">ehCache</span>" /> 
      </property> 
    </bean> 
     
    <bean id="methodCachePointCut" class="org.springframework.<span class="hilite2" style="background-color:rgb(85,255,85)">aop</span>.support.RegexpMethodPointcutAdvisor"> 
      <property name="advice"> 
        <ref local="methodCacheInterceptor"/> 
      </property> 
      <property name="patterns"> 
        <list> 
            <value>.*find.*</value> 
            <value>.*get.*</value> 
        </list> 
      </property> 
    </bean> 
    <bean id="methodCachePointCutAdvice" class="org.springframework.<span class="hilite2" style="background-color:rgb(85,255,85)">aop</span>.support.RegexpMethodPointcutAdvisor"> 
      <property name="advice"> 
        <ref local="methodCacheAfterAdvice"/> 
      </property> 
      <property name="patterns"> 
        <list> 
          <value>.*create.*</value> 
          <value>.*update.*</value> 
          <value>.*delete.*</value> 
        </list> 
      </property> 
    </bean> 
</beans> 

上面的代码最终创建了两个"切入点",methodCachePointCut和methodCachePointCutAdvice,分别用于拦截不同方法名的方法,可以根据需要任意增加所需要拦截方法的名称。
需要注意的是
Java代码


[java] view plaincopy
<bean id="<span class="hilite3" style="background-color:rgb(170,255,170)">ehCache</span>" class="org.springframework.cache.<span class="hilite3" style="background-color:rgb(170,255,170)">ehcache</span>.EhCacheFactoryBean"> 
      <property name="cacheManager"> 
        <ref local="defaultCacheManager"/> 
      </property> 
      <property name="cacheName"> 
          <value>DEFAULT_CACHE</value> 
      </property> 
    </bean> 

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

事实上到了这里,一个简单的Spring + ehCache Framework基本完成了,为了测试效果,举一个实际应用的例子,定义一个TestService和它的实现类TestServiceImpl,里面包含

两个方法getAllObject()和updateObject(Object Object),具体代码如下
TestService.java
Java代码
 

[java] view plaincopy
package com.co.cache.test; 
 
import java.util.List; 
 
public interface TestService { 
    public List getAllObject(); 
 
    public void updateObject(Object Object); 



TestServiceImpl.java
Java代码
[java] view plaincopy
package com.co.cache.test; 
 
import java.util.List; 
 
public class TestServiceImpl implements TestService 

    public List getAllObject() { 
        System.out.println("---TestService:Cache内不存在该element,查找并放入Cache!"); 
        return null; 
    } 
 
    public void updateObject(Object Object) { 
        System.out.println("---TestService:更新了对象,这个Class产生的cache都将被remove!"); 
    } 


使用Spring提供的AOP进行配置
applicationContext.xml
Java代码
[java] view plaincopy
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//<span class="hilite1" style="background-color:rgb(255,255,0)">SPRING</span>//DTD BEAN//EN" "http://www.springframework.org/dtd/<span class="hilite1" style="background-color:rgb(255,255,0)">spring</span>-beans.dtd"> 
 
<beans> 
    <import resource="cacheContext.xml"/> 
     
    <bean id="testServiceTarget" class="com.co.cache.test.TestServiceImpl"/> 
     
    <bean id="testService" class="org.springframework.<span class="hilite2" style="background-color:rgb(85,255,85)">aop</span>.framework.ProxyFactoryBean"> 
      <property name="target"> 
          <ref local="testServiceTarget"/> 
      </property> 
      <property name="interceptorNames"> 
        <list> 
          <value>methodCachePointCut</value> 
          <value>methodCachePointCutAdvice</value> 
        </list> 
      </property> 
    </bean> 
</beans> 

这里一定不能忘记import cacheContext.xml文件,不然定义的两个拦截器就没办法使用了。

最后,写一个测试的代码
MainTest.java
Java代码

[java] view plaincopy
package com.co.cache.test; 
 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
public class MainTest{ 
    public static void main(String args[]){ 
        String DEFAULT_CONTEXT_FILE = "/applicationContext.xml"; 
        ApplicationContext context =  new ClassPathXmlApplicationContext(DEFAULT_CONTEXT_FILE); 
        TestService testService = (TestService)context.getBean("testService"); 
 
        System.out.println("1--第一次查找并创建cache"); 
        testService.getAllObject(); 
         
        System.out.println("2--在cache中查找"); 
        testService.getAllObject(); 
         
        System.out.println("3--remove cache"); 
        testService.updateObject(null); 
         
        System.out.println("4--需要重新查找并创建cache"); 
        testService.getAllObject(); 
    }    



运行,结果如下
Java代码
1--第一次查找并创建cache  
---TestService:Cache内不存在该element,查找并放入Cache!  
2--在cache中查找  
3--remove cache  
---TestService:更新了对象,这个Class产生的cache都将被remove!  
4--需要重新查找并创建cache  
---TestService:Cache内不存在该element,查找并放入Cache! 
[java] view plaincopy
大功告成 .可以看到,第一步执行getAllObject(),执行TestServiceImpl内的方法,并创建了cache,在第二次执行getAllObject()方法时,由于cache有该方法的缓存,直接从cache中get出方法的结果,所以没有打印出TestServiceImpl中的内容,而第三步,调用了updateObject方法,和TestServiceImpl相关的cache被remove,所以在第四步执行时,又执行TestServiceImpl中的方法,创建Cache。  
 
网上也有不少类似的例子,但是很多都不是很完备,自己参考了一些例子的代码,其实在<span class="hilite1" style="background-color:rgb(255,255,0)">spring</span>-modules中也提供了对几种cache的支持,<span class="hilite3" style="background-color:rgb(170,255,170)">ehCache</span>,OSCache,JBossCache这些,看了一下,基本上都是采用类似的方式,只不过封装的更完善一些,主要思路也还是<span class="hilite1" style="background-color:rgb(255,255,0)">Spring</span>的<span class="hilite2" style="background-color:rgb(85,255,85)">AOP</span>,有兴趣的可以研究一下。
分享到:
评论

相关推荐

    整合spring 和ehcache

    配置ehcache缓存,存储内存的设置,与spring 的整合等

    spring整合EhCache 基于注解的方式

    本例子主要讲解ehcache的配置使用。采用了java配置和xml配置两种方式。主要用于学习。 使用java配置时将SpringTestCase.java 文件中的@ContextConfiguration(locations = { "classpath:applicationContext.xml" }) ...

    spring+ehcache+mabatis

    spring+ehcache+mabatis。测试用例用的是mysql,数据库的配置在jdbc.properties里面。所要的sql在src/main/resources下的student.sql。测试的话调用controller下的update和getOne那两个接口测试。

    Struts2+Spring+Hibernate+Ehcache+AJAX+JQuery+Oracle 框架集成用户登录注册Demo工程

    1.通过google ehcache-spring-annotatios.jar自动注解方式实现整合Spring+Ehcache。 2.Action里通过struts2-spring-plugin.jar插件自动根据名字注入。 3.Ajax无刷新异步调用Struts2,返回Json数据,以用户注册为例。...

    Spring 使用注解配置使用ehcache

    NULL 博文链接:https://cuisuqiang.iteye.com/blog/2050675

    spring整合EhCache 基于注解

    本例子主要讲解ehcache的配置使用。采用了java配置和xml配置两种方式。主要用于学习。 使用java配置时将SpringTestCase.java 文件中的@ContextConfiguration(locations = { "classpath:applicationContext.xml" }) ...

    SpringMVC+Mybatis+Spring+Shiro+ehcache整合配置文件

    SpringMVC+Mybatis+Spring+Shiro+ehcache整合配置文件

    Spring4 整合EhCache实现 页面缓存 零配置

    以java配置类方式 整合EhCache来实现页面整体缓存及页面局部缓存。详情见博客http://blog.csdn.net/poorCoder_/article/details/56483954

    Spring + Ehcache 注解形式配置

    NULL 博文链接:https://miaoxianjie.iteye.com/blog/1704619

    Spring+EHcache缓存实例详解

    在使用 EHCache 缓存时,我们需要在 Spring 配置文件中添加 EHCache 的配置,例如: ``` &lt;bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"&gt; ...

    spring+shiro+ehcache例子

    在web.xml中配置spring容器的监听器。 2:项目集成springmvc 在web.xml中配置前端控制器 3:项目集成shiro 在web.xml中配置shiro过滤器 4:项目post乱码处理 在web.xml中配置字符过滤器 5:项目运行...

    详解Spring整合Ehcache管理缓存

    首先,需要在 Spring 配置文件中启用缓存并指定 Ehcache 为缓存管理器: ```xml &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:...

    springmvc4+spring4+hibernate5.1.3+二级缓存ehcache+fastjson配置

    此配置和包,是springMVC4.3.3 +spring4+hibernate5.1.3+二级缓存ehcache(不用可以关闭)+fastjson。 是正常运行的项目里拷出来的,方便大家使用。

    spring ehcache

    该项目使用了spring cache第三方插件ehcache ,是一个完整的项目其中涉及一张表,需要用户自己根据mybatis的配置xml自行在数据库中添加一张表,使用的是spring3 xml配置方式,希望对你们有帮助,有问题,我可以邮箱...

    Spring搭配Ehcache实例解析

    -- 在Spring配置文件中引入Ehcache配置 --&gt; &lt;import resource="classpath:ehcache.xml" /&gt; &lt;!-- 配置Ehcache bean --&gt; &lt;bean id="cacheManager" class="org.springframework.cache.ehcache....

    Spring整合JBPM、日志、数据库、ehcache的配置文件

    框架整合配置文件:Spring整合JBPM、日志、数据库、ehcache的配置文件

    配置Spring+hibernate使用ehcache作为second-levelcache.docx

    " Spring+Hibernate 使用 Ehcache 作为 Second-Level Cache" Spring 和 Hibernate 是 Java Web 应用程序开发中两个非常重要的技术栈。Spring 是一个轻量级的控制反转(IoC)容器,提供了一个框架来管理 Java 对象...

    Spring+MyBatis/Hibernate+Ehcache+Maven的Demo Web项目(稳定版)

    1.标题所提及技术的整合,Spring包括mvc、aop、ioc等。个人属于强迫症类型,技术水平怎么样再说,代码必须好看 2.Hibernate几个级别缓存对比。见DaoImpl类 3.Ehcache方法缓存及页面缓存。见applicationContext-cache...

    Hibernate+EhCache配置及使用说明详解

    EhCache 是 Hibernate 的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力。 EhCache 的使用注意点: 1. 当用 Hibernate 的方式修改表数据...

    Spring 缓存

    使用 Spring 与 Ehcache 结合,需要在应用程序中配置 Ehcache,并使用 Spring 的注解对指定的方法进行缓存。Ehcache 是一个流行的开源缓存框架,提供了强大的缓存功能。 在 Ehcache 中,需要配置缓存的设置,例如...

Global site tag (gtag.js) - Google Analytics