今天學習Spring 緩存機制。遇到不少問題~
好不easy緩存的單元測試用例調試成功了,在同一項目下單元測試另外一個文件時,發生了異常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cacheManagerFactory' defined in file [D:\workspaces\eclipse_svn\NewsPortalProject\WebContent\WEB-INF\classes\config\ehcache.applicationContext.xml]: Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following: 1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary 2. Shutdown the earlier cacheManager before creating new one with same name.
因為項目下有三個配置文件。都放在同一文件夾下:
在另個單元測試用例中實例化Spring容器的時候,全部的配置文件都載入進去了
ApplicationContext aCtx = new FileSystemXmlApplicationContext("classpath:config/*.xml");
解決的方法:將緩存的配置文件和其它的配置文件放在不同包下
1.緩存測試用例中。實例化容器時,僅僅讀緩存相關的配置文件;
ApplicationContext aCtx = new FileSystemXmlApplicationContext("classpath:ehcache/*.xml");2.其它用例也僅僅讀自己的配置文件。
ApplicationContext aCtx = new FileSystemXmlApplicationContext("classpath:config/*.xml");
配置文件路徑:/project/src/test/resources/ehcache
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="10" timeToLiveSeconds="10" overflowToDisk="false"/> <cache name="cachelist" eternal="false" timeToIdleSeconds="360" timeToLiveSeconds="3600" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" memoryStoreEvictionPolicy="LRU" /> </ehcache>
ehcache.applicationContext.xml
<?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:oxm="http://www.springframework.org/schema/oxm" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <!-- 緩存 屬性--> <context:component-scan base-package="com.test" /> <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache/ehcache.xml"/> </bean> <!-- 支持緩存注解 --> <cache:annotation-driven cache-manager="cacheManager" /> <!-- 默認是cacheManager --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" > <property name="cacheManager" ref="cacheManagerFactory"/> </bean> </beans>
package com.test.news.util; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; /** * * 項目名稱:NewsPortalProject * 類名稱:DirectcityCacheTest * 類描寫敘述: * 創建人:XianJuanJuan * 創建時間:2015年6月2日 下午2:11:45 * @version * */ public class DirectcityCacheTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @SuppressWarnings("resource") @Test public void init() { ApplicationContext aCtx = new FileSystemXmlApplicationContext("classpath:ehcache/*.xml"); CacheManager cacheManager = (CacheManager) aCtx.getBean("cacheManager"); // 為了測試緩存是否成功,這里加一個 for (int i = 0; i<5;i++) { Object obj = cacheManager.getCache("newslist").get("a1"); String data = null; if (obj == null) { System.out.println("i="+i+";第一次運行該方法,緩存中還沒有數據"); } else { data = (String) cacheManager.getCache("newslist").get("a1").get(); System.out.println("i="+i+";第"+i+"次讀到的緩存中的內容:"+cacheManager.getCache("newslist").get("a1").get()); } String list = ""+i; if (data == null) { list = list + "String"; if(list != null && !"".equals(list)) { Cache cache = cacheManager.getCache("newslist"); if (cache != null) { cache.put("a1", list); } } } } } }
結果:

單元測試調試好的代碼,放在resin下一跑。類似異常又發生了。經過一番周折之后,最終見着曙光了~
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false" > <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="10" timeToLiveSeconds="10" overflowToDisk="false"/> <cache name="cachelist" eternal="false" timeToIdleSeconds="360" timeToLiveSeconds="3600" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" memoryStoreEvictionPolicy="LRU" /> </ehcache>
我靠,最終攻克了,原來是ehcache版本號的問題。ehcache-core2.5.0之前的版本號不會出問題。2.5.0及之后會報這個異常。我選了個ehcache-core2.4.8的好使。
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.8</version>
</dependency>
看官方的文檔說明:
Versions of Ehcache before version 2.5 allowed any number of CacheManagers with the same name (same configuration resource) to exist in a JVM.
Ehcache 2.5 and higher does not allow multiple CacheManagers with the same name to exist in the same JVM. CacheManager() constructors creating non-Singleton CacheManagers can violate this rule
至此,Spring 中的ehcache緩存的問題全然攻克了~