誰說java代碼多,5分鐘搞定app緩存

字號:


    概述:我用了5分鐘為自己的app(應(yīng)用程序)添加緩存,再一次證明java也不需要寫長篇的代碼,就能為app添加緩存。想知道我怎樣做的嗎?請看下文。
    你也許永遠不會相信我為應(yīng)用程序添加緩存層,只用了5分鐘。
    我的應(yīng)用程序使用 spring version 3.2.8 和 maven 3.2.1。
    從spring version 3.2 開始,org.springframework.cache.ehcache已經(jīng)從核心寶中移除,現(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}
    步驟二
    在應(yīng)用程序中將以下代碼加入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></cache:annotation-driven></bean></bean>
    步驟三
    將ehcache.xml添加到類路徑
    一個基本的ehcache.xml入下:
    <ehcache xmlns:xsi=>
    <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> </persistence></cache>
    </defaultcache></diskstore></ehcache>
    步驟四
    最后一步,使用注釋,非常簡單,一行代碼:
    @cacheable(value =youcache)
    這個注釋可以使用任何方法,默認情況下在緩存哈希圖中,它使用方法參數(shù)作為key。
    現(xiàn)在,誰說java要寫長篇的代碼?
    ehcache介紹:
    在這次實踐中使用了ehcache,它強大、高度可定制化,可以根據(jù)需要設(shè)置任何key、緩存類型、緩存時間。最重要的是,他開源