本文将构建一个普通工程来说明spring注解缓存的使用方式,关于如何在web应用中使用注解缓存,请参见:

Spring基于注解的缓存配置--web应用实例

一.简介
在spring的modules包中提供对许多第三方缓存方案的支持,包括:
EHCache
OSCache(OpenSymphony)
JCS
GigaSpaces
JBoss Cache
等等。
将这些第三方缓存方案配置在spring中很简单,网上有许多介绍,这里只重点介绍如何配置基于注解的缓存配置。
本文将通过例举EHCache和OSCache详细介绍如何使用spring配置基于注解的缓存配置,注意这里的缓存是方法级的。

二.依赖
在开始介绍如何进行缓存配置前先介绍一下EHCache和OSCache的jar依赖。
EHCache:
ehcache-core-1.7.2.jar
jakarta-oro-2.0.8.jar
slf4j-api-1.5.8.jar
slf4j-jdk14-1.5.8.jar

OSCache:
oscache-2.4.1.jar

此外,两者都需要的jar如下:
cglib-nodep-2.1_3.jar
commons-logging.jar
log4j-1.2.15.jar
spring-modules-cache.jar
spring.jar

三.配置

两种缓存在spring配置文件中都可以使用两种配置方式,一种是spring2.0以前的完全基于bean的复杂配置,一种是使用后来的基于命名空间的简单配置,两种配置效果相同,分别介绍如下:

EHCache:
1)普通配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- aop代理,这个是必须地,否则缓存不起作用 -->
<bean id="autoproxy"
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" /> <!-- EhCache 管理工厂 用于指定ehcache配置文件路径 -->
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>
<bean id="cacheProviderFacade" class="org.springmodules.cache.provider.ehcache.EhCacheFacade">
<property name="cacheManager" ref="cacheManager" />
</bean> <!-- 1.5+ Annotation 基于注解查找被缓存的业务方法 -->
<bean id="cachingAttributeSource"
class="org.springmodules.cache.annotations.AnnotationCachingAttributeSource"></bean>
<!-- 缓存拦截器:定义了缓存模块,ehcache只需要指定配置文件中的缓存名称 -->
<bean id="cachingInterceptor"
class="org.springmodules.cache.interceptor.caching.MetadataCachingInterceptor">
<property name="cacheProviderFacade" ref="cacheProviderFacade" />
<property name="cachingAttributeSource" ref="cachingAttributeSource" />
<property name="cachingModels">
<props>
<prop key="testCaching">cacheName=testCache</prop>
</props>
</property>
</bean> <!-- 基于注解查找缓存业务方法的AOP通知器 -->
<bean id="cachingAttributeSourceAdvisor"
class="org.springmodules.cache.interceptor.caching.CachingAttributeSourceAdvisor">
<constructor-arg ref="cachingInterceptor" />
</bean> <!-- 基于注解查找触发缓存刷新动作的业务方法 -->
<bean id="flushingAttributeSource"
class="org.springmodules.cache.annotations.AnnotationFlushingAttributeSource"></bean> <!-- 刷新拦截器:定义了刷新策略,基于那个模块ID,刷新相应的缓存 -->
  <bean id="flushingInterceptor"
class="org.springmodules.cache.interceptor.flush.MetadataFlushingInterceptor">
<property name="cacheProviderFacade" ref="cacheProviderFacade" />
<property name="flushingAttributeSource" ref="flushingAttributeSource" />
<property name="flushingModels">
<map>
<entry key="testFlushing">
<bean
class="org.springmodules.cache.provider.ehcache.EhCacheFlushingModel"> <property name="cacheNames">
<list>
<value>testCache</value>
</list>
</property> <!-- 报错,应该是不能直接设置cacheName
<property name="cacheName" value="testCache"/>
-->
</bean>
</entry>
</map> </property>
</bean> <!-- 基于注解查找刷新缓存业务方法的AOP通知器 -->
<bean id="flushingAttributeSourceAdvisor"
class="org.springmodules.cache.interceptor.flush.FlushingAttributeSourceAdvisor">
<constructor-arg ref="flushingInterceptor" />
</bean> <!-- 测试对象 -->
<bean id="testCache" class="com.TestCache"/> </beans>

2)命名空间配置

<?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:ehcache="http://www.springmodules.org/schema/ehcache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"> <!-- 这里可以不需要配置这个
<bean id="autoproxy" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
--> <ehcache:config configLocation="classpath:ehcache.xml"
id="cacheProvider" />
<ehcache:annotations providerId="cacheProvider">
<ehcache:caching cacheName="testCache" id="testCaching" />
<ehcache:flushing cacheNames="testCache" id="testFlushing" />
</ehcache:annotations> <bean id="testCache" class="com.TestCache"/> </beans>

OSCache:
1)普通配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 这个是必须地,否则缓存不起作用 -->
<bean id="autoproxy"
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" /> <!-- 缓存管理工厂:使用OSCache缓存管理,配置了OSCache使用的配置文件路径 -->
<bean id="cacheManager"
class="org.springmodules.cache.provider.oscache.OsCacheManagerFactoryBean">
<property name="configLocation" value="classpath:oscache.properties" />
</bean>
<!-- 缓存提供:OSCache -->
<bean id="cacheProviderFacade" class="org.springmodules.cache.provider.oscache.OsCacheFacade">
<property name="cacheManager" ref="cacheManager" />
</bean> <!-- 1.5+ Annotation 基于注解查找被缓存的业务方法 -->
<bean id="cachingAttributeSource"
class="org.springmodules.cache.annotations.AnnotationCachingAttributeSource"></bean> <!-- 缓存拦截器:定义了缓存模块,以及相应的刷新策略,以及缓存所属群组 -->
  <bean id="cachingInterceptor"
class="org.springmodules.cache.interceptor.caching.MetadataCachingInterceptor">
<property name="cacheProviderFacade" ref="cacheProviderFacade" />
<property name="cachingAttributeSource" ref="cachingAttributeSource" />
<property name="cachingModels">
<props>
<prop key="testCaching">refreshPeriod=86400;cronExpression=0 1 * * *;groups=pb_test</prop>
</props>
</property>
</bean> <!-- 基于注解查找缓存业务方法的AOP通知器 -->
<bean id="cachingAttributeSourceAdvisor"
class="org.springmodules.cache.interceptor.caching.CachingAttributeSourceAdvisor">
<constructor-arg ref="cachingInterceptor" />
</bean> <!-- 基于注解查找触发缓存刷新动作的业务方法 -->
<bean id="flushingAttributeSource"
class="org.springmodules.cache.annotations.AnnotationFlushingAttributeSource"></bean> <!-- 刷新拦截器:定义了刷新策略,基于那个模块ID,刷新相应的缓存群组 -->
<bean id="flushingInterceptor"
class="org.springmodules.cache.interceptor.flush.MetadataFlushingInterceptor">
<property name="cacheProviderFacade" ref="cacheProviderFacade" />
<property name="flushingAttributeSource" ref="flushingAttributeSource" />
<property name="flushingModels">
<props>
<prop key="testFlushing">groups=pb_test</prop>
</props>
</property>
</bean> <!-- 基于注解查找刷新缓存业务方法的AOP通知器 -->
<bean id="flushingAttributeSourceAdvisor"
class="org.springmodules.cache.interceptor.flush.FlushingAttributeSourceAdvisor">
<constructor-arg ref="flushingInterceptor" />
</bean> <bean id="testCache" class="com.TestCache"/> </beans>

2)命名空间配置

<?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:oscache="http://www.springmodules.org/schema/oscache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springmodules.org/schema/oscache http://www.springmodules.org/schema/cache/springmodules-oscache.xsd"> <!-- 这里可以不需要配置这个
<bean id="autoproxy" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
--> <oscache:config configLocation="classpath:oscache.properties" id="cacheProvider"/> <oscache:annotations providerId="cacheProvider">
<oscache:caching id="testCaching" groups="pb_test" cronExpression="0 1 * * *" refreshPeriod="86400"/>
<oscache:flushing id="testFlushing" groups="pb_test"/>
</oscache:annotations> <bean id="testCache" class="com.TestCache"/> </beans>

四.注解

@Cacheable:声明一个方法的返回值应该被缓存

例如:@Cacheable(modelId = "testCaching")

@CacheFlush:声明一个方法是清空缓存的触发器

例如:@CacheFlush(modelId = "testCaching")

五.测试

这是用使用一个带有main函数的类来进行测试,代码如下:

/*
* COPYRIGHT Beijing NetQin-Tech Co.,Ltd. *
****************************************************************************
* 源文件名: TestCache.java
* 功能: (描述文件功能)
* 版本: @version 1.0
* 编制日期: 2010-2-24
* 说明: (描述使用文件功能时的制约条件)
* 修改历史: (主要历史变动原因及说明)
* YYYY-MM-DD | Author | Change Description
* 2010-2-24 | hanqunfeng | Created
*/
package com; import net.sf.ehcache.CacheManager; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springmodules.cache.annotations.CacheFlush;
import org.springmodules.cache.annotations.Cacheable; import com.opensymphony.oscache.general.GeneralCacheAdministrator; public class TestCache { /**
* 描述 : <描述函数实现的功能>. <br>
*<p> * @param args
*/
static String context = null;
static ApplicationContext applicationContext; static{
context = "applicationContext-ehcache.xml";//ehcache简单配置(命名空间)
// context = "applicationContext-ehcache_full.xml";//ehcache完整配置
// context = "applicationContext-oscache.xml";//oscache简单配置(命名空间)
// context = "applicationContext-oscache_full.xml";//oscache完整配置 applicationContext = new ClassPathXmlApplicationContext(context);
}
public static void main(String[] args) {
TestCache test = (TestCache)applicationContext.getBean("testCache");
System.out.println(test.getName(0));
System.out.println(test.getName(0));
System.out.println(test.getName(0));
test.flush();
// test.OSFlushAll();
// test.EHFlushAll();
System.out.println(test.getName(0));
System.out.println(test.getName(0));
System.out.println(test.getName(0)); }
@Cacheable(modelId = "testCaching")
public String getName(int i){
System.out.println("Processing testCaching");
return "nihao:"+i;
} @CacheFlush(modelId = "testFlushing")
public void flush(){
System.out.println("Processing testFlushing");
} /**
* 描述 : <OSCache刷新全部缓存>. <br>
*<p>
问题:flushAll() 后不会再缓存数据
*/
public void OSFlushAll(){
GeneralCacheAdministrator cacheAdmin = (GeneralCacheAdministrator)applicationContext.getBean("cacheManager");
cacheAdmin.flushAll();
System.out.println("Processing OSFlushingAll");
} /**
* 描述 : <清空指定组名称的缓存>. <br>
*<p> * @param groupName
*/
public void OSFlushGroup(String groupName){
GeneralCacheAdministrator cacheAdmin = (GeneralCacheAdministrator)applicationContext.getBean("cacheManager");
cacheAdmin.flushGroup(groupName);//清除该组的缓存:pb_test
System.out.println("Processing OSFlushingGroup:"+groupName);
} /**
* 描述 : <EHCache刷新全部缓存>. <br>
*<p>
success
*/
public void EHFlushAll(){
CacheManager cacheAdmin = (CacheManager)applicationContext.getBean("cacheManager");
cacheAdmin.clearAll();
System.out.println("Processing EHFlushingAll");
} /**
* 描述 : <清空指定名称的缓存>. <br>
*<p> * @param cacheName
*/
public void EHFlushCache(String cacheName){
CacheManager cacheAdmin = (CacheManager)applicationContext.getBean("cacheManager");
cacheAdmin.getCache(cacheName).flush();//清除单个缓存:testCache
System.out.println("Processing EHFlushingCacheName:"+cacheName);
} }

测试结果

Processing testCaching
nihao:0
nihao:0
nihao:0
Processing testFlushing
Processing testCaching
nihao:0
nihao:0
nihao:0

六.缓存配置文件

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<cache name="testCache"
maxElementsInMemory="10000"
maxElementsOnDisk="1000"
eternal="false"
overflowToDisk="true"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
/>
</ehcache>

oscache.properties

    1. cache.capacity=5000

缓存初解(三)---Spring3.0基于注解的缓存配置+Ehcache和OScache的更多相关文章

  1. 缓存初解(五)---SpringMVC基于注解的缓存配置--web应用实例

    之前为大家介绍了如何使用spring注解来进行缓存配置 (EHCache 和 OSCache)的简单的例子,详见 Spring基于注解的缓存配置--EHCache AND OSCache 现在介绍一下 ...

  2. spring和ehcache整合,实现基于注解的缓存实现

    要实现基于注解的缓存实现,要求Spring的版本在3.1或以上版本. 首先需要在spring的配置文件中添加对缓存注解的实现: <?xml version="1.0" enc ...

  3. Struts2基于注解的Action配置

    使用注解来配置Action的最大好处就是可以实现零配置,但是事务都是有利有弊的,使用方便,维护起来就没那么方便了. 要使用注解方式,我们必须添加一个额外包:struts2-convention-plu ...

  4. 8 -- 深入使用Spring -- 4...5 AOP代理:基于注解的“零配置”方式

    8.4.5 基于注解的“零配置”方式 AspectJ允许使用注解定义切面.切入点和增强处理,而Spring框架则可识别并根据这些注解来生成AOP代理.Spring只是使用了和AspectJ 5 一样的 ...

  5. 10 Spring框架--基于注解的IOC配置

    1.工程环境搭建 2.基于注解的IOC配置 IOC注解的分类 (1)用于创建对象的 他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的@Component: 作用: ...

  6. spring-第十七篇之spring AOP基于注解的零配置方式

    1.基于注解的零配置方式 Aspect允许使用注解定义切面.切入点和增强处理,spring框架可以识别并根据这些注解来生成AOP代理.spring只是用了和AspectJ 5一样的注解,但并没有使用A ...

  7. java web学习总结(二十一) -------------------模拟Servlet3.0使用注解的方式配置Servlet

    一.Servlet的传统配置方式 在JavaWeb开发中, 每次编写一个Servlet都需要在web.xml文件中进行配置,如下所示: 1 <servlet> 2 <servlet- ...

  8. JavaWeb学习总结(四十八)——模拟Servlet3.0使用注解的方式配置Servlet

    一.Servlet的传统配置方式 在JavaWeb开发中, 每次编写一个Servlet都需要在web.xml文件中进行配置,如下所示: 1 <servlet> 2 <servlet- ...

  9. 基于注解的形式配置Bean

    基于注解的方式配置Bean:也就说我们在每个Bean的类名前面注解一下,Spring会自动帮我们扫描Bean放进IOC容器中 I基于注解的方式配置Bean(没有依赖关系的Bean)有两个步骤: 1组件 ...

随机推荐

  1. linux命令详解之useradd命令

    useradd命令使用方法,还包括用户账号的添加.删除与修改.用户口令的管理.用户组的管理方法. Linux系统是一个多用户多任务的分时操作系统,任何一个要使用系统资源的用户,都必须首先向系统管理员申 ...

  2. 查看SQL Server 备份信息

    RESTORE HEADERONLY FROM DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQL2008\MSSQL\Back ...

  3. 关于使用视图进行分页时出现当前记录集不支持书签的错误解决方法及原因(asp)

    一般在使用视图进行查询时,视图中意般都关联了两个或者更多个表,一般在这种情况下才会使用视图,但是但我在使用视图来查询数据时没有问题,但是一旦在分页中使用到视图进行查询就会出现错误提示如下: ADODB ...

  4. hadoop的核心思想

    hadoop的核心思想 1.1.1. hadoop的核心思想 Hadoop包括两大核心,分布式存储系统和分布式计算系统. 1.1.1.1. 分布式存储 为什么数据需要存储在分布式的系统中哪,难道单一的 ...

  5. 游刃于MVC、WCF中的Autofac

    为了程序的健壮性.扩展性.可维护性,依赖抽象而不是具体实现类等等,于是我选择了Autofac依赖注入容器 就是这个工厂来降低耦合.之前买东西是自己去超市,现在呢 我需要什么东西,他们给送过来直接拿到了 ...

  6. NSRange、NSPoint(CGPoint)、NSSize(CGSize)、NSRect(CGRect)

    1.NSRange: typedef struct _NSRange { NSUInteger location; NSUInteger length; } NSRange; NSRange本身是系统 ...

  7. VBS基础篇 - 数组

    数组变量:有时需要向一个单一的变量赋于多个值,那么您可以创建一个可包含一系列值的变量,这种变量被称为数组. '静态数组 ) a()="George" a()="john& ...

  8. extern "C"——用“C”来规约在C++中用C的方式进行编译和链接

    C++中的extern “C”用法详解     extern "C"表明了一种编译规约,其中extern是关键字属性,“C”表征了编译器链接规范.对于extern "C& ...

  9. SCRUM团队的三个角色

    Scrum团队中包括三个角色,他们分别是产品负责人.开发团队和 Scrum Master. Scrum 团队是自组织.跨职能的完整团队.自组织团队决定如何最好地完成他们的工作,而不是由团队外的其他人来 ...

  10. 3223: Tyvj 1729 文艺平衡树 - BZOJ

    Description 您需要写一种数据结构(可参考题目标题),来维护一个有序数列,其中需要提供以下操作:翻转一个区间,例如原有序序列是5 4 3 2 1,翻转区间是[2,4]的话,结果是5 2 3 ...