本文參考網上多篇文章整合。
1.需要的jar包
ehcache-core-2.5.2.jar slf4j-api-1.6.1.jar cglib-2.2.jar [----這個包可能是不需要的] ehcache-spring-annotations-1.1.2.jar aopalliance.jar
2.在spring的設定檔applicationContext.xml中配置ehcache
<ehcache:annotation-driven cache-manager="ehCacheManager" /> <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:conf/<span style="color:#ff0000;">ehcache.xml</span>" /> </bean>
3.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"> <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" /> <cache name="messageCache" maxElementsInMemory="10" eternal="true" overflowToDisk="false" /> <cache name="messagesCache" maxElementsInMemory="10" eternal="true" overflowToDisk="false" /></ehcache>
至此,ehcache的配置完成。 使用demo進行測試
import java.io.Serializable;import net.sf.ehcache.Cache;import net.sf.ehcache.CacheManager;import net.sf.ehcache.Element;public abstract class Ehcache_Demo { /** * @param args */ //static CacheManager manager= new CacheManager(); /** *############################################################################## * * @DESCRIBE * @param args * @throws InterruptedException * *############################################################################## */ public static void main(String[] args) throws InterruptedException { CacheManager manager = new CacheManager("resource/conf/ehcache.xml"); String[] cacheNames = manager.getCacheNames(); System.out.println(System.getProperty("java.io.tmpdir")); System.out.println("讀取的緩衝列表為:"); for(int i=0;i<cacheNames.length;i++){ System.out.println("-- "+(i+1)+" "+cacheNames[i]); } Cache cache = manager.getCache("messageCache"); Element element = new Element("key1", "value1"); cache.put(element); element = cache.get("key1"); Serializable value = element.getValue(); System.out.println("序列化後的值為:"+value.toString()); element = cache.get("key1"); Object value1 = element.getObjectValue(); System.out.println("未序列化的值為:"+value1.toString()); int elementsInMemory = cache.getSize(); System.out.println("得到緩衝的對象數量:"+elementsInMemory); long elementsInMemory1 = cache.getMemoryStoreSize(); System.out.println("得到緩衝對象佔用記憶體的數量:"+elementsInMemory1); long elementsInMemory2 = cache.getDiskStoreSize(); System.out.println("得到緩衝對對象佔用磁碟的數量:"+elementsInMemory2); }} 輸出結果: C:\Users\ADMINI~1\AppData\Local\Temp\ 讀取的緩衝列表為: -- 1 messageCache -- 2 messagesCache 序列化後的值為:value1 未序列化的值為:value1 得到緩衝的對象數量:1 得到緩衝對象佔用記憶體的數量:1 得到緩衝對對象佔用磁碟的數量:0