原創(chuàng)|使用教程|編輯:龔雪|2014-11-06 09:51:36.000|閱讀 1565 次
概述:我用了5分鐘為自己的App(應用程序)添加緩存,再一次證明Java也不需要寫長篇的代碼,就能為App添加緩存。想知道我怎樣做的嗎?請看下文。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
你也許永遠不會相信我為應用程序添加緩存層,只用了5分鐘。
我的應用程序使用 Spring version 3.2.8 和 maven 3.2.1。
從Spring version 3.2 開始,org.springframework.cache.ehcache已經從核心寶中移除,現(xiàn)在在spring-context-support中。為了讓EhCache工作,你必須單獨添加在項目中。
maven需要添加下面代碼:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency>
以及
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency>
將最新版本放到占位符中: ${spring.version} 和 ${ehcache.version}
在應用程序中將以下代碼加入context.xml:
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache"/> <bean id="ehcache" class="org.springframework.cache.ehcache. EhCacheManagerFactoryBean" p:configLocation="classpath:configuration/ehcache.xml" p:shared="true"/> <cache:annotation-driven/>
將ehcache.xml添加到類路徑
一個基本的ehcache.xml入下:
<ehcache xmlns:xsi="//www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="//ehcache.org/ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <defaultCache /> <cache name="yourCache" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="1800" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="1800" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </cache> </ehcache>
最后一步,使用注釋,非常簡單,一行代碼:
@Cacheable(value = "youCache")
這個注釋可以使用任何方法,默認情況下在緩存哈希圖中,它使用方法參數(shù)作為key。
現(xiàn)在,誰說Java要寫長篇的代碼?
EhCache介紹:
在這次實踐中使用了EhCache,它強大、高度可定制化,可以根據(jù)需要設置任何key、緩存類型、緩存時間。最重要的是,他開源。
無處不在的廣告,關注一下真會省不少錢
【年終大促 巔峰盛"慧" 】促銷火熱進行中 iPhone 6 Plus、 iPhone 6、iPad Air等你拿 點我查看
FastReport VCL 5新版發(fā)布會,2014-11-25 15:00網絡直播,免費參加?
標簽:JavaMaven
本站文章除注明轉載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:慧都控件網