Java 5分钟搞定App缓存

版权所有,禁止匿名转载;禁止商业使用。

我用了5分钟为自己的App(应用程序)添加缓存,再一次证明Java也不需要写长篇的代码,就能为App添加缓存。想知道我怎样做的吗?请看下文。

你也许永远不会相信我为应用程序添加缓存层,只用了5分钟。


我的应用程序使用 Spring version 3.2.8 和 maven 3.2.1。


从Spring version 3.2 开始,org.springframework.cache.ehcache已经从核心宝中移除,现在在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></cache:annotation-driven></bean></bean>

步骤三


将ehcache.xml添加到类路径


一个基本的ehcache.xml入下:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation="http://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"> </persistence></cache>
</defaultcache></diskstore></ehcache>

步骤四


最后一步,使用注释,非常简单,一行代码:

@Cacheable(value = "youCache")

这个注释可以使用任何方法,默认情况下在缓存哈希图中,它使用方法参数作为key。


现在,谁说Java要写长篇的代码?


EhCache介绍:


在这次实践中使用了EhCache,它强大、高度可定制化,可以根据需要设置任何key、缓存类型、缓存时间。最重要的是,他开源。


0 0