以 EHCache 为例:需要额外添加的 jar 包:
1)、ehcache-1.2.3.jar
2)、commons-logging-1.1.1:下载链接: https://pan.baidu.com/s/1hskP2xY 密码: u1zs
4. 一级缓存和二级缓存和查询缓存
a) 什么是缓存;
b) 什么是一级缓存:session级别的缓存;
c) 什么是二级缓存:SessionFactory级别的缓存,可以跨越 session 存在;
适合放在缓存的数据
i. 经常被访问
ii. 改动不大不会经常改动
iii. 数量有限
d) 打开二级缓存
i. hibernate.cfg.xml设定:
1 <property name="cache.use_second_level_cache">true</property> 2 3 <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
ii. @Cache 注解
1 @Entity 2 @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)//一般用READ_WRITE,可读写 3 public class Category { 4 ... 5 }
e) load默认使用二级缓存,iterate默认使用二级缓存;
f) list默认往二级缓存加数据,但是查询的时候不使用;
g) 如果要 query 用二级缓存,需打开查询缓存。
i. <property name="cache.use_query_cache">true</property>
ii. 调用 Query 的 setCachable(true)方法指明使用二级缓存
1 List<Category> categories = (List<Category>)session.createQuery("from Category") 2 .setCacheable(true).list(); 3 List<Category> categories2 = (List<Category>)session.createQuery("from Category") 4 .setCacheable(true).list();
h) 缓存算法:(纯为了面试)
i. LRU、LFU、FIFO
1. Least Recently Used
2. Least Frequently Used (命中率高低)
3. First In First Out
ii. memoryStoreEvictionPolicy="LRU" (ehcache)
jar包链接: https://pan.baidu.com/s/1dFsxg21 密码: xqnm
代码链接: https://pan.baidu.com/s/1c15ajXQ 密码: r6n5