我的日常

登录/注册
您现在的位置:论坛 盖世程序员(我猜到了开头 却没有猜到结局) 盖世程序员 > 如何配置Hibernate中的二级缓存
总共48087条微博

动态微博

查看: 1127|回复: 0

如何配置Hibernate中的二级缓存

[复制链接]

279

主题

41

听众

689

金钱

版主

该用户从未签到

跳转到指定楼层
楼主
发表于 2015-07-18 22:13:11 |只看该作者 |倒序浏览
需要启动二级缓存,二级缓存的scope是sessionFactory。也就是说二级缓存的数据可以在由相同SessionFactory创建的多个Session中重用。3 ?& {, C5 O- U; M+ v
6 f2 r/ n* ?/ [$ X. g5 X
首先,要在hibernate.cfg.xml中设置一个cache Provider,hibernate支持多个cache实现,有EHCache,OSCache等。在非分布式环境中可以选择默认的EHCache。添加ehcahe jar$ [& g& O  F- s9 ]4 H/ u. t
  1. <dependency>4 g  h" @" q4 i# S* S& Q
  2.           <groupId>org.hibernate</groupId>
    2 f$ k6 w9 B9 }
  3.           <artifactId>hibernate-ehcache</artifactId>
    ' k- L% n. @2 M. X: @
  4.           <version>4.3.5.Final</version>. ~3 V& ^' ?+ J3 R
  5.       </dependency>
复制代码
  1. <hibernate-configuration>6 N# |$ q0 e2 h: G! g
  2.     <session-factory>; n6 ]- R4 J* w7 x8 m( o
  3.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>( B: \8 F  o" c) n( m7 x
  4.         <property name="connection.url">jdbc:mysql://localhost/test</property>
    3 w- f3 G" C- ~3 Q/ b5 h
  5.         <property name="connection.username">root</property>
    * M9 Q5 G* n' {7 Q# O& F* y
  6.         <property name="connection.password"></property>
    " c( t: q1 J& ~6 a# f( S2 q
  7.         <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    7 ^- F( h; C7 o: V2 ^% G8 }
  8.         <property name="hibernate.show_sql">true</property>7 f" l% D. W5 W/ R1 U. q% T
  9.         <property name="hibernate.hbm2ddl.auto">update</property>0 v; e1 a5 b, V& P6 c2 J+ y) [* w
  10.         <property name="hibernate.generate_statistics">true</property>
    6 S5 k$ ~- b: n1 S" h
  11.         <property name="hibernate.cache.region.factory_class">
    8 t- w& u8 L. H# S  U$ @
  12.             org.hibernate.cache.ehcache.EhCacheRegionFactory
    " S' H3 z) i6 W6 ~# C' _
  13.         </property>
    0 A; N5 o+ X: R! ?$ E, _
  14.         <mapping class="com.xinglongjian.entity.hbm.Book2"/>
    2 u' ]/ E) \3 z# c0 G/ f7 s4 Z
  15. </hibernate-configuration>
复制代码
  W! G( z' s  s% B0 z
第二,通过ehcache.xml配置EHCache,该文件放置于classpath的根目录下。可以在该配置文件中设置将不同的对象存储在不同的regions。
  1. <ehcache>
    ) O$ W5 ]( w& b+ }, V7 H
  2. <diskStore path="c:/data/ehcache"/>
    % ?) X3 U, w6 y
  3. <defaultCache9 ?. t' T6 H2 W$ L$ J
  4.         maxElementsInMemory="10"' L- Y3 ?- f0 @$ |
  5.         eternal="false"
    ( i; ?9 a; B- w$ V: T, V1 x
  6.         overflowToDisk="true"
    ' P0 ^; ?% u: {2 ?2 u, S
  7.         timeToIdleSeconds="120". V# |2 I2 R' x! j, Q/ \! b) q
  8.         timeToLiveSeconds="120"
    ( u8 X: D# i: Z* T9 N
  9.         diskPersistent="false"; c% c; C+ j# A$ G8 O. F8 J- P: X
  10.         diskExpiryThreadIntervalSeconds="120"/>
    : c7 Y' u4 h) i: _: ?# t, a
  11. <cache name="com.xinglongjian.entity.hbm.Book" maxElementsInMemory="10"  eternal="false"
    4 _0 S! y3 M0 ~/ T( Z5 S
  12.     overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskPersistent="false"/>" k, E* c/ J) t7 C& G
  13. </ehcache>
复制代码
第三,设置持久化类
  1. @Entity3 j. d' s4 x/ B- ~! E# t6 M
  2. @Cacheable9 |; F) H" ]" E- B3 h/ l
  3. @Cache(usage=CacheConcurrencyStrategy.READ_ONLY,region="com.xinglongjian.entity.hbm.Book")' D! f1 g: X2 f0 R& ~/ u" V
  4. public class Book2 {
    ) d8 i8 N" ~. n" Q8 k
  5.     @Id
    * _8 {2 N* E; V) k: e# A
  6.     @GeneratedValue
    2 z3 b* `3 ]* Z$ [
  7.     private int id;4 K" }- T/ z' P. p
  8.     private String title;
    1 ^4 S% _) [* `
  9.     public String getTitle() {
    * c3 k  {/ l+ f& K: O8 t& Z# p
  10.         return title;5 Q' w" v9 S" \+ v: s% A
  11.     }+ X* E/ n7 N  Z% E% F7 V2 k- T5 E
  12.     public void setTitle(String title) {
    3 o, d; s7 B! w" G5 @! K  x
  13.         this.title = title;
    $ @4 D1 i9 r3 o
  14.     }
    3 D! n# t1 G6 ]* H! i0 e9 R2 L  Z
  15.     public int getId() {: N$ Z5 v& d- P: C# `( B
  16.         return id;2 v" M/ l* m" ~4 J* [& |
  17.     }* b4 |1 A5 n: N/ t5 M9 a
  18.     public void setId(int id) {
    ) N# m5 z! t" a! g
  19.         this.id = id;
    / a" V1 o1 Z* C( Y( u* H1 q
  20.     }
    : y: _( d" |# X5 ~5 Z0 k, ]& U
  21.     @Override' T7 N9 `, A! ^" ^$ R% F
  22.     public int hashCode() {
    * m3 {1 W+ [: q, c+ m9 G) g
  23.         final int prime = 31;- o3 I+ _2 W( g! z
  24.         int result = 1;, x" s* M3 e- `1 {
  25.         result = prime * result + id;
    $ v# L7 E8 y; l8 c
  26.         result = prime * result + ((title == null) ? 0 : title.hashCode());1 ~' n: S" ^, ], @7 ?/ l# Y
  27.         return result;# j8 o0 j1 D/ N# w; I
  28.     }
    ' Q, |; ?" r2 ]) {
  29.     @Override5 J, c1 z0 \# X4 s; R) P
  30.     public boolean equals(Object obj) {8 D3 \8 \8 N3 a3 ]: ^- F
  31.         if (this == obj)) m: [# C0 [! d9 A$ V! ]
  32.             return true;
    , _. Y8 X  I. E2 L. `
  33.         if (obj == null)
    ) V/ B! ]- z0 V$ x. j  x
  34.             return false;
    0 L% ?+ E2 u0 P8 w
  35.         if (getClass() != obj.getClass())4 H' r* v, }$ W8 |" V
  36.             return false;
    " T+ t: N8 j* S, U5 v5 t' W& @
  37.         Book2 other = (Book2) obj;
    : O- S! s5 m- d% o
  38.         if (id != other.id)  x: X4 `% U; l  k( Y$ Z6 F
  39.             return false;; c" s+ b" ~( D5 j5 b
  40.         if (title == null) {4 R: |/ R# G* V, c# q
  41.             if (other.title != null)
    5 i2 D& i' e$ a2 M3 ^1 B# M8 B; q
  42.                 return false;& N6 M9 b" ]' T8 o1 q
  43.         } else if (!title.equals(other.title))- y/ i5 z, c( C
  44.             return false;. @5 L. t# }4 T" ]. s
  45.         return true;
    4 t  S' x0 e& Z4 _4 @
  46.     }
    : T7 a  J! [1 D; _0 _3 `
  47.     % ~5 Q# {7 P1 h: s
  48. }
复制代码
二级缓存的持久化类必须实现equals方法。' m; R: x) ]; L- G
% Q! A% h9 J' `/ X1 ?9 t
只有在SELECT时才会缓存。
% ?( s+ T9 U4 u6 c0 W, U1 P
$ a& v5 K' j+ t! n3 }在同一个session里,查询2个不同的对象,会缓存2次,
  1. Session sess=sf.openSession();( e4 w+ b, c( Q- F, A3 `" j
  2.         Book2 b=(Book2) sess.get(Book2.class, 17);9 k2 U6 v& M: g% Y% B6 W0 s! k
  3.         System.out.println(b);
    7 b! h+ R1 w5 T
  4.         assertEquals("spring Recipes", b.getTitle());
    " t. R0 C3 l: E, u2 V$ O1 S; i
  5.         Book2 b3=(Book2) sess.get(Book2.class, 18);
    6 m( L; l! A3 Q7 b
  6.         assertEquals("dfad", b3.getTitle());& _4 Z5 q% y5 `( p# k( j) }6 T5 X
  7.         sess.close();
    4 W: M; s# b7 p
  8.         slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");
    0 [+ r" |8 _. @
  9.         System.out.println(slcs);
复制代码
结果
  1. SecondLevelCacheStatistics[hitCount=0,missCount=2,putCount=2,elementCountInMemory=2,elementC
    ( \9 \. I8 j7 h+ L3 \) D" C( ?' _
  2. ountOnDisk=0,sizeInMemory=3948]
复制代码

) ~) n3 M# u& F# a* ~% W; z* m 在同一个session里,查询相同的对象,会先查询一级缓存,一级缓存中有就不会查询二级缓存。
  1. Session sess1=sf.openSession();: a; e, F- C( y4 I
  2.         Book2 b1=(Book2) sess1.get(Book2.class, 17);
    & e+ b# L. v3 U6 y% h4 S
  3.         System.out.println(b);
    " \- I5 v9 L& B" s1 W
  4.         Book2 b2=(Book2) sess1.get(Book2.class, 17);  e, j: z. n6 q" _- b8 A
  5.         assertEquals("Spring Recipes", b1.getTitle());1 g9 o, D; Q, B( O& Z7 [# J
  6.         assertEquals("Spring Recipes", b2.getTitle());
      }2 X# o9 b6 h
  7.         slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");
    . G( f2 Z1 S- Q$ q
  8.         System.out.println(slcs);
复制代码
结果,在新的session中,一级缓存不可用,就会使用二级缓存。
  1. SecondLevelCacheStatistics[hitCount=1,missCount=2,putCount=2,elementCountInMemory=2,elementC" {/ _& N+ N! [2 |+ W
  2. ountOnDisk=0,sizeInMemory=3948]
复制代码
完整测试逻辑
  1. @Test* w% y, E1 Q  O! b8 h
  2.     public void test2LCache()
    ( ~$ ?8 T, E9 P& K. ?8 p# p
  3.     {
    + j4 ^5 G; H  W) Z. d5 U. j
  4.         Statistics stat=sf.getStatistics();//获取stat对象9 I$ h7 ~: }. n% S' s! s( Y
  5.         Session sess=sf.openSession();6 ^) @( g8 V6 W: _- K
  6.         Transaction tx=sess.beginTransaction();1 M/ D* G2 H+ u& l- A% T
  7.         
    8 T/ H. ~% d) M" P
  8.         //存储对象,此时不会放到缓存中
    ! x! K+ d" L& j7 N* ]6 B# T& l0 g
  9.         System.out.println("--------------存储对象---------------------------------");5 P! ?- f! A  ^. {( S
  10.         Book2 book=new Book2();
      J3 ]; W1 l1 f' f: b* i, u* d
  11.         book.setTitle("Spring Recipes");0 S5 e: n/ r" f0 Z
  12.         sess.saveOrUpdate(book);
    ! z) [  _. K5 p! R  l
  13.         tx.commit();7 B8 S# Y/ N/ w0 G1 ]
  14.         sess.close();  G& j8 M7 a9 T: G1 q* |6 Y4 Z
  15.         System.out.println(book);
    ) E" C3 t# j6 X+ d. m* s  r. `
  16.         SecondLevelCacheStatistics slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");  q% g8 ?. Y% c# S
  17.         System.out.println(slcs);
    2 R, `0 m( `# K0 J8 U. g
  18.         Cache cache=sf.getCache();7 [+ j7 A- Q  H9 G, d4 M
  19.         System.out.println(cache);
    4 H8 l- ]$ ]+ k
  20.         cache.evictAllRegions();//从所有region中获取数据
    9 ]7 m- u) n( _* ?
  21.         Map map=slcs.getEntries();) M( m3 h* @+ j% z: @* `
  22.         System.out.println("Cache entries:"+map.size());/ x  n% j. O" R5 |8 a
  23.         System.out.println("--------------第一次查询后---------------------------------");" v& r+ j' B! ^: F/ |1 v, Y
  24.         sess=sf.openSession();: a2 A% N0 ], r9 P; S6 A
  25.         tx=sess.beginTransaction();& p) w+ ?7 t6 F( x, V( @- B6 @
  26.         Book2 b1=(Book2) sess.byId(Book2.class).load(book.getId());//第一次查询
    2 [4 m* H! v5 W, O$ P
  27.         System.out.println(b1);
    , ^. c3 P8 ]$ n3 R+ B
  28.         assertEquals(book, b1);; B/ X. c! s$ k. B& X' ]4 s: X
  29.         tx.commit();
    # ]* d" q" M2 O7 a# x6 T
  30.         sess.close();
    9 }, Y3 k; g$ E' I8 N
  31.         slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");2 }. W# L. y2 O+ l6 N" T
  32.         System.out.println(slcs);0 f6 X: }+ w3 K4 E) n) s
  33.         map=slcs.getEntries();
    ( r! h# D" I; l
  34.         System.out.println(map.size());
    2 \* A0 h+ S, s+ _7 D0 S$ [" N: {4 I
  35.         System.out.println("--------------第二次查询后---------------------------------");7 I& g+ @: C* }; w) n
  36.         sess=sf.openSession();
    + v$ D7 e* W% e
  37.         tx=sess.beginTransaction();
    ! n6 h4 M2 Z( z- D( F7 j
  38.         Book2 b2=(Book2) sess.byId(Book2.class).load(book.getId());//第二次查询
    " a) n6 K! Z$ x2 h0 ^
  39.         System.out.println(b2);
    * E6 d( L* ^: G% |
  40.         assertEquals(book, b2);
    # ~+ M$ l: v# f2 u- G
  41.         tx.commit();
    1 U* G6 M( e8 f7 V* X) [
  42.         sess.close();( ~6 r2 g; L2 j" J: t; B5 r4 W
  43.         
    + X& I7 S6 [0 x/ P3 m
  44.         slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");* t- b' c' G* v: z+ ]
  45.         System.out.println(slcs);
    % \- x. ]- I4 R5 G. g: n  v1 ]$ h
  46.         // this is the initial select+ d6 ]/ k) g5 X
  47.         assertEquals(stat.getSecondLevelCacheMissCount(), 1);
      [9 t' l6 g- J( O5 {$ ]
  48.         // we put one element in the cache from the miss
    6 N5 }3 o7 `- ?% @+ R
  49.         assertEquals(stat.getSecondLevelCachePutCount(), 1);
    : ?+ L. ~/ \' S4 E3 k5 {& L. _, ?: n
  50.         // we still didn't hit the cache, because of 1L cache# B$ V+ x2 w5 ], ?/ |$ |
  51.         assertEquals(stat.getSecondLevelCacheHitCount(), 1);
    + e; p3 ~# E0 Q6 d6 H
  52.         System.out.println("--------------第三次查询后---------------------------------");
    % [% k. T7 f  D
  53.         sess=sf.openSession();
    % i: V' \. F+ ?; O  i! T) j  [# u
  54.         tx=sess.beginTransaction();
    1 U1 A/ \: _* f" l1 ]
  55.         b1=(Book2) sess.byId(Book2.class).load(book.getId());//第三次查询1 m- G( b( i8 w0 R: n$ ]# w
  56.         assertEquals(book, b1);  Q/ k/ d, [, E: j0 u/ T. e3 \8 ^
  57.         tx.commit();
    $ a; \# z9 L: G
  58.         sess.close();
    ' t0 Z# n! h/ G( ?1 o$ p8 y( h# W
  59.         8 O$ A; X3 M, d$ T4 T% }
  60.         slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");
    3 k6 F. I8 l, ]# C/ E, {) S
  61.         System.out.println(slcs);
    * |! T+ g7 I0 r, P9 V5 O* Y! H
  62.         // same miss count (we should hit now). C- ^& o, O. K
  63.         assertEquals(stat.getSecondLevelCacheMissCount(), 1);) s3 [" [8 M  U- C/ t
  64.         // same put count (we didn't put anything new)! h% p$ T! o+ P. C
  65.         assertEquals(stat.getSecondLevelCachePutCount(), 1);7 H) D* F; H6 ^% [
  66.         // now we hit the 2L cache for load5 I! b$ g, R* \; K$ |% |
  67.         assertEquals(stat.getSecondLevelCacheHitCount(), 2);
    % X0 z0 e4 C1 A- J/ |" L
  68.         
    9 |& S$ u3 B; j6 |( _- ?0 i9 d
  69.     }
复制代码
完整测试结果
  1. Hibernate: delete from book2
    4 j% }; n4 t' C9 R9 G0 z
  2. --------------存储对象---------------------------------' C' ?- k2 P- h8 T( b! `
  3. Hibernate: insert into Book2 (title) values (?)1 k7 c; r! N* N8 \, z% k8 Q/ X
  4. com.xinglongjian.entity.hbm.Book2@521e083b
    9 x: H4 O2 Y  D9 B9 y
  5. SecondLevelCacheStatistics[hitCount=0,missCount=0,putCount=0,elementCountInMemory=0,elementCountOnDisk=0,sizeInMemory=0]' c: Q' L* P! x/ r% C
  6. org.hibernate.internal.CacheImpl@4830f6
    & Z2 C. f* H/ w
  7. Cache entries:07 H' D% y; [) l* m! [7 o' Z
  8. --------------第一次查询后---------------------------------4 `) K# _; }$ u. I" s
  9. Hibernate: select book2x0_.id as id1_0_0_, book2x0_.title as title2_0_0_ from Book2 book2x0_
    4 e$ F6 C3 Z0 V
  10. where book2x0_.id=?
    * |  }/ k5 V! M& S: b0 I
  11. com.xinglongjian.entity.hbm.Book2@521e083b
    $ ^1 n9 ^8 H. ]3 Z( [
  12. SecondLevelCacheStatistics[hitCount=0,missCount=1,putCount=1,elementCountInMemory=1,elementC
    % W! T. l( o& _
  13. ountOnDisk=0,sizeInMemory=1979]' _8 v+ j' D$ K# J' a
  14. 1& `/ E, e" @6 K' }
  15. --------------第二次查询后---------------------------------
    : s) e% Z1 U9 p- i
  16. com.xinglongjian.entity.hbm.Book2@521e083b
    1 Z2 n8 y: f) s) q  ~# I0 G) j
  17. SecondLevelCacheStatistics[hitCount=1,missCount=1,putCount=1,elementCountInMemory=1,elementC2 Q% F5 }% s# w8 T
  18. ountOnDisk=0,sizeInMemory=1979]
      z) m9 g9 E4 g9 {  K; Z
  19. --------------第三次查询后---------------------------------9 l& H! D: T% z: w
  20. SecondLevelCacheStatistics[hitCount=2,missCount=1,putCount=1,elementCountInMemory=1,elementC0 b- S0 \1 y* E+ B
  21. ountOnDisk=0,sizeInMemory=1979]
复制代码
, v4 V. q/ }' u

科帮网 1、本主题所有言论和图片纯属会员个人意见,与本社区立场无关
2、本站所有主题由该帖子作者发表,该帖子作者与科帮网享有帖子相关版权
3、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者和科帮网的同意
4、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任
5、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责
6、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意
7、科帮网管理员和版主有权不事先通知发贴者而删除本文


JAVA爱好者①群:JAVA爱好者① JAVA爱好者②群:JAVA爱好者② JAVA爱好者③ : JAVA爱好者③

快速回复
您需要登录后才可以回帖 登录 | 立即注册

   

关闭

站长推荐上一条 /1 下一条

发布主题 快速回复 返回列表 联系我们 官方QQ群 科帮网手机客户端
快速回复 返回顶部 返回列表