Spring基于注解的缓存配置--EHCache AND OSCache

本文将构建一个普通工程来说明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代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!-- aop代理,这个是必须地,否则缓存不起作用 -->
  7. <bean id="autoproxy"
  8. class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
  9. <!-- EhCache 管理工厂 用于指定ehcache配置文件路径 -->
  10. <bean id="cacheManager"
  11. class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  12. <property name="configLocation" value="classpath:ehcache.xml" />
  13. </bean>
  14. <bean id="cacheProviderFacade" class="org.springmodules.cache.provider.ehcache.EhCacheFacade">
  15. <property name="cacheManager" ref="cacheManager" />
  16. </bean>
  17. <!-- 1.5+ Annotation 基于注解查找被缓存的业务方法 -->
  18. <bean id="cachingAttributeSource"
  19. class="org.springmodules.cache.annotations.AnnotationCachingAttributeSource"></bean>
  20. <!-- 缓存拦截器:定义了缓存模块,ehcache只需要指定配置文件中的缓存名称 -->
  21. <bean id="cachingInterceptor"
  22. class="org.springmodules.cache.interceptor.caching.MetadataCachingInterceptor">
  23. <property name="cacheProviderFacade" ref="cacheProviderFacade" />
  24. <property name="cachingAttributeSource" ref="cachingAttributeSource" />
  25. <property name="cachingModels">
  26. <props>
  27. <prop key="testCaching">cacheName=testCache</prop>
  28. </props>
  29. </property>
  30. </bean>
  31. <!-- 基于注解查找缓存业务方法的AOP通知器 -->
  32. <bean id="cachingAttributeSourceAdvisor"
  33. class="org.springmodules.cache.interceptor.caching.CachingAttributeSourceAdvisor">
  34. <constructor-arg ref="cachingInterceptor" />
  35. </bean>
  36. <!-- 基于注解查找触发缓存刷新动作的业务方法 -->
  37. <bean id="flushingAttributeSource"
  38. class="org.springmodules.cache.annotations.AnnotationFlushingAttributeSource"></bean>
  39. <!-- 刷新拦截器:定义了刷新策略,基于那个模块ID,刷新相应的缓存 -->
  40. <bean id="flushingInterceptor"
  41. class="org.springmodules.cache.interceptor.flush.MetadataFlushingInterceptor">
  42. <property name="cacheProviderFacade" ref="cacheProviderFacade" />
  43. <property name="flushingAttributeSource" ref="flushingAttributeSource" />
  44. <property name="flushingModels">
  45. <map>
  46. <entry key="testFlushing">
  47. <bean
  48. class="org.springmodules.cache.provider.ehcache.EhCacheFlushingModel">
  49. <property name="cacheNames">
  50. <list>
  51. <value>testCache</value>
  52. </list>
  53. </property>
  54. <!-- 报错,应该是不能直接设置cacheName
  55. <property name="cacheName" value="testCache"/>
  56. -->
  57. </bean>
  58. </entry>
  59. </map>
  60. </property>
  61. </bean>
  62. <!-- 基于注解查找刷新缓存业务方法的AOP通知器 -->
  63. <bean id="flushingAttributeSourceAdvisor"
  64. class="org.springmodules.cache.interceptor.flush.FlushingAttributeSourceAdvisor">
  65. <constructor-arg ref="flushingInterceptor" />
  66. </bean>
  67. <!-- 测试对象 -->
  68. <bean id="testCache" class="com.TestCache"/>
  69. </beans>
<?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代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  6. http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd">
  7. <!-- 这里可以不需要配置这个
  8. <bean id="autoproxy" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
  9. -->
  10. <ehcache:config configLocation="classpath:ehcache.xml"
  11. id="cacheProvider" />
  12. <ehcache:annotations providerId="cacheProvider">
  13. <ehcache:caching cacheName="testCache" id="testCaching" />
  14. <ehcache:flushing cacheNames="testCache" id="testFlushing" />
  15. </ehcache:annotations>
  16. <bean id="testCache" class="com.TestCache"/>
  17. </beans>
<?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代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!-- 这个是必须地,否则缓存不起作用 -->
  7. <bean id="autoproxy"
  8. class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
  9. <!-- 缓存管理工厂:使用OSCache缓存管理,配置了OSCache使用的配置文件路径 -->
  10. <bean id="cacheManager"
  11. class="org.springmodules.cache.provider.oscache.OsCacheManagerFactoryBean">
  12. <property name="configLocation" value="classpath:oscache.properties" />
  13. </bean>
  14. <!-- 缓存提供:OSCache -->
  15. <bean id="cacheProviderFacade" class="org.springmodules.cache.provider.oscache.OsCacheFacade">
  16. <property name="cacheManager" ref="cacheManager" />
  17. </bean>
  18. <!-- 1.5+ Annotation 基于注解查找被缓存的业务方法 -->
  19. <bean id="cachingAttributeSource"
  20. class="org.springmodules.cache.annotations.AnnotationCachingAttributeSource"></bean>
  21. <!-- 缓存拦截器:定义了缓存模块,以及相应的刷新策略,以及缓存所属群组 -->
  22. <bean id="cachingInterceptor"
  23. class="org.springmodules.cache.interceptor.caching.MetadataCachingInterceptor">
  24. <property name="cacheProviderFacade" ref="cacheProviderFacade" />
  25. <property name="cachingAttributeSource" ref="cachingAttributeSource" />
  26. <property name="cachingModels">
  27. <props>
  28. <prop key="testCaching">refreshPeriod=86400;cronExpression= 1 * * *;groups=pb_test</prop>
  29. </props>
  30. </property>
  31. </bean>
  32. <!-- 基于注解查找缓存业务方法的AOP通知器 -->
  33. <bean id="cachingAttributeSourceAdvisor"
  34. class="org.springmodules.cache.interceptor.caching.CachingAttributeSourceAdvisor">
  35. <constructor-arg ref="cachingInterceptor" />
  36. </bean>
  37. <!-- 基于注解查找触发缓存刷新动作的业务方法 -->
  38. <bean id="flushingAttributeSource"
  39. class="org.springmodules.cache.annotations.AnnotationFlushingAttributeSource"></bean>
  40. <!-- 刷新拦截器:定义了刷新策略,基于那个模块ID,刷新相应的缓存群组 -->
  41. <bean id="flushingInterceptor"
  42. class="org.springmodules.cache.interceptor.flush.MetadataFlushingInterceptor">
  43. <property name="cacheProviderFacade" ref="cacheProviderFacade" />
  44. <property name="flushingAttributeSource" ref="flushingAttributeSource" />
  45. <property name="flushingModels">
  46. <props>
  47. <prop key="testFlushing">groups=pb_test</prop>
  48. </props>
  49. </property>
  50. </bean>
  51. <!-- 基于注解查找刷新缓存业务方法的AOP通知器 -->
  52. <bean id="flushingAttributeSourceAdvisor"
  53. class="org.springmodules.cache.interceptor.flush.FlushingAttributeSourceAdvisor">
  54. <constructor-arg ref="flushingInterceptor" />
  55. </bean>
  56. <bean id="testCache" class="com.TestCache"/>
  57. </beans>
<?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代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oscache="http://www.springmodules.org/schema/oscache"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  6. http://www.springmodules.org/schema/oscache http://www.springmodules.org/schema/cache/springmodules-oscache.xsd">
  7. <!-- 这里可以不需要配置这个
  8. <bean id="autoproxy" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
  9. -->
  10. <oscache:config configLocation="classpath:oscache.properties" id="cacheProvider"/>
  11. <oscache:annotations providerId="cacheProvider">
  12. <oscache:caching id="testCaching" groups="pb_test" cronExpression="0 1 * * *" refreshPeriod="86400"/>
  13. <oscache:flushing id="testFlushing" groups="pb_test"/>
  14. </oscache:annotations>
  15. <bean id="testCache" class="com.TestCache"/>
  16. </beans>
<?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函数的类来进行测试,代码如下:

Java代码 复制代码 收藏代码
  1. /*
  2. * COPYRIGHT Beijing NetQin-Tech Co.,Ltd. *
  3. ****************************************************************************
  4. * 源文件名: TestCache.java
  5. * 功能: (描述文件功能)
  6. * 版本: @version 1.0
  7. * 编制日期: 2010-2-24
  8. * 说明: (描述使用文件功能时的制约条件)
  9. * 修改历史: (主要历史变动原因及说明)
  10. * YYYY-MM-DD | Author | Change Description
  11. * 2010-2-24 | hanqunfeng | Created
  12. */
  13. package com;
  14. import net.sf.ehcache.CacheManager;
  15. import org.springframework.context.ApplicationContext;
  16. import org.springframework.context.support.ClassPathXmlApplicationContext;
  17. import org.springmodules.cache.annotations.CacheFlush;
  18. import org.springmodules.cache.annotations.Cacheable;
  19. import com.opensymphony.oscache.general.GeneralCacheAdministrator;
  20. public class TestCache {
  21. /**
  22. * 描述 : <描述函数实现的功能>. <br>
  23. *<p>
  24. * @param args
  25. */
  26. static String context = null;
  27. static ApplicationContext applicationContext;
  28. static{
  29. context = "applicationContext-ehcache.xml";//ehcache简单配置(命名空间)
  30. // context = "applicationContext-ehcache_full.xml";//ehcache完整配置
  31. // context = "applicationContext-oscache.xml";//oscache简单配置(命名空间)
  32. // context = "applicationContext-oscache_full.xml";//oscache完整配置
  33. applicationContext = new ClassPathXmlApplicationContext(context);
  34. }
  35. public static void main(String[] args) {
  36. TestCache test = (TestCache)applicationContext.getBean("testCache");
  37. System.out.println(test.getName());
  38. System.out.println(test.getName());
  39. System.out.println(test.getName());
  40. test.flush();
  41. // test.OSFlushAll();
  42. // test.EHFlushAll();
  43. System.out.println(test.getName());
  44. System.out.println(test.getName());
  45. System.out.println(test.getName());
  46. }
  47. @Cacheable(modelId = "testCaching")
  48. public String getName(int i){
  49. System.out.println("Processing testCaching");
  50. return "nihao:"+i;
  51. }
  52. @CacheFlush(modelId = "testFlushing")
  53. public void flush(){
  54. System.out.println("Processing testFlushing");
  55. }
  56. /**
  57. * 描述 : <OSCache刷新全部缓存>. <br>
  58. *<p>
  59. 问题:flushAll() 后不会再缓存数据
  60. */
  61. public void OSFlushAll(){
  62. GeneralCacheAdministrator cacheAdmin = (GeneralCacheAdministrator)applicationContext.getBean("cacheManager");
  63. cacheAdmin.flushAll();
  64. System.out.println("Processing OSFlushingAll");
  65. }
  66. /**
  67. * 描述 : <清空指定组名称的缓存>. <br>
  68. *<p>
  69. * @param groupName
  70. */
  71. public void OSFlushGroup(String groupName){
  72. GeneralCacheAdministrator cacheAdmin = (GeneralCacheAdministrator)applicationContext.getBean("cacheManager");
  73. cacheAdmin.flushGroup(groupName);//清除该组的缓存:pb_test
  74. System.out.println("Processing OSFlushingGroup:"+groupName);
  75. }
  76. /**
  77. * 描述 : <EHCache刷新全部缓存>. <br>
  78. *<p>
  79. success
  80. */
  81. public void EHFlushAll(){
  82. CacheManager cacheAdmin = (CacheManager)applicationContext.getBean("cacheManager");
  83. cacheAdmin.clearAll();
  84. System.out.println("Processing EHFlushingAll");
  85. }
  86. /**
  87. * 描述 : <清空指定名称的缓存>. <br>
  88. *<p>
  89. * @param cacheName
  90. */
  91. public void EHFlushCache(String cacheName){
  92. CacheManager cacheAdmin = (CacheManager)applicationContext.getBean("cacheManager");
  93. cacheAdmin.getCache(cacheName).flush();//清除单个缓存:testCache
  94. System.out.println("Processing EHFlushingCacheName:"+cacheName);
  95. }
  96. }
/*
* 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代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
  4. monitoring="autodetect">
  5. <diskStore path="java.io.tmpdir"/>
  6. <defaultCache
  7. maxElementsInMemory="10000"
  8. eternal="false"
  9. timeToIdleSeconds="120"
  10. timeToLiveSeconds="120"
  11. overflowToDisk="true"
  12. maxElementsOnDisk="10000000"
  13. diskPersistent="false"
  14. diskExpiryThreadIntervalSeconds="120"
  15. memoryStoreEvictionPolicy="LRU"
  16. />
  17. <cache name="testCache"
  18. maxElementsInMemory="10000"
  19. maxElementsOnDisk="1000"
  20. eternal="false"
  21. overflowToDisk="true"
  22. diskSpoolBufferSizeMB="20"
  23. timeToIdleSeconds="300"
  24. timeToLiveSeconds="600"
  25. memoryStoreEvictionPolicy="LFU"
  26. />
  27. </ehcache>

你可能感兴趣的:(Spring基于注解的缓存配置--EHCache AND OSCache)