概述:我用了5分钟为自己的app(应用程序)添加缓存,再一次证明java也不需要写长篇的代码,就能为app添加缓存。想知道我怎样做的吗?请看下文。/ y/ ?2 l6 z2 b+ H# B
你也许永远不会相信我为应用程序添加缓存层,只用了5分钟。8 y% V" p; s% w* E S
我的应用程序使用 spring version 3.2.8 和 maven 3.2.1。% [5 @ p2 H$ f3 m. V2 [: v
从spring version 3.2 开始,org.springframework.cache.ehcache已经从核心宝中移除,现在在spring-context-support中。为了让ehcache工作,你必须单独添加在项目中。5 Q! P& F# A/ a
步骤一, v& J5 c% \/ c% {
maven需要添加下面代码:) m6 H6 x# M9 K7 s! \
<dependency>9 m B4 S' F& o( `, b6 {6 f; Q
<groupid>org.springframework</groupid>
, E8 }( q" k. m2 u) I<artifactid>spring-context-support</artifactid> <version>${spring.version}</version>
% J" F, x1 V: s8 c</dependency>
; i8 j4 _2 x6 Q" v以及
+ q9 u) {3 }7 t; b3 Y9 m<dependency>
2 w# X# Z/ z+ T<groupid>net.sf.ehcache</groupid>
' `, a& N8 t8 b5 I<artifactid>ehcache</artifactid>
# `! D3 r9 U8 I/ r3 S9 @& v<version>${ehcache.version}</version>
% i3 q" g; q P, F9 Y/ J c( X</dependency>
9 T* H+ e2 ^% ~. M将最新版本放到占位符中: ${spring.version} 和 ${ehcache.version}
# r: v3 q9 {* `% }5 G8 K2 P! U步骤二; z2 y' O% y- S' E, [
在应用程序中将以下代码加入context.xml:
$ A( |7 p: h! K<bean id=cachemanager class=org.springframework.cache.ehcache.ehcachecachemanager p:cachemanager-ref=ehcache>1 L! X8 d( H# i. H: X# ^! u6 W, I
<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>
9 @. k0 o, N7 C' [ r, d# z步骤三 t# v& D- w c- [( p
将ehcache.xml添加到类路径) G; d6 F D5 P) f! }6 ?0 ~
一个基本的ehcache.xml入下:
c5 H `# A* s5 F<ehcache xmlns:xsi=>
. a9 p# G- [2 F' s6 ^6 i<diskstore path=java.io.tmpdir>; V! w( m) c3 ^3 I, L; n
<defaultcache>
+ P. s+ e& I* {<cache name=yourcache maxelementsinmemory=10000 eternal=false timetoidleseconds=1800 timetoliveseconds=1800 maxelementsondisk=10000000 diskexpirythreadintervalseconds=1800 memorystoreevictionpolicy=lru> <persistence strategy=localtempswap> </persistence></cache>' w. T: E( \3 R0 [* }8 L
</defaultcache></diskstore></ehcache>
3 L+ U; R! f3 |$ |步骤四: t( s5 f% L3 j% Q: Q7 O5 q: Q
最后一步,使用注释,非常简单,一行代码:; E/ M" ~ h: Y# }, B" K# W
@cacheable(value =youcache)& H+ d1 [, S; C- @
这个注释可以使用任何方法,默认情况下在缓存哈希图中,它使用方法参数作为key。+ q: x6 V8 O/ `6 I3 k% ]
现在,谁说java要写长篇的代码?$ K9 k1 C. p, [/ }0 I: [
ehcache介绍:7 W. I- G* f' N: R
在这次实践中使用了ehcache,它强大、高度可定制化,可以根据需要设置任何key、缓存类型、缓存时间。最重要的是,他开源1 d) Q# y8 {6 U3 g
6 E; b: i# x& {4 S" ]2 i3 m# M% Z
更多网页制作信息请查看: 网页制作 |
|