谁说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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值