谁说java代码多,5分钟搞定app缓存

  • 格式:doc
  • 大小:15.50 KB
  • 文档页数:2

概述:我用了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=>
<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、缓存类型、缓存时间。

最重要的是,他开源
更多信息请查看IT技术专栏。