为什么要使用二级缓存
因为一级缓存有限(生命周期短,大批量操作数据可能造成内存溢出),我们需要二级缓存来弥补不足
1,需要配置
2,交给了第三方处理
3,二级缓存插件(常见):
hashtable, osCache ,EHcache
4,二级缓存可能放在内存中,或磁盘上
5,二级缓存可使用的策略:read-only,read-write(最好使用这个),nonstrict-read-write
不严格读写,transactional事务缓存
二级缓存还可以通过配置,来获取命中率等信息,要通过sessionFactory获得
<property name="hibernate.generate_statistics">true</property>
//完成统计了,在这里测试命中率问题ps:HibernateUtil使自己写的工具类,这里就获取了sessionFactory,也可以直接获取,不写工具类 Statistics statistics = HibernateUtil.getSessionFactory().getStatistics(); System.out.println(statistics);//打印所有信息 //打印具体信息 System.out.println("放入的次数=="+statistics.getSecondLevelCachePutCount()); System.out.println("错过的次数=="+statistics.getSecondLevelCacheMissCount()); System.out.println("命中的次数=="+statistics.getSecondLevelCacheHitCount());
6,可以oscache.properties文件放在src目录下,这样可以指定放入二级缓存对象capacity大小,默认1000
7,例子:EHcache作为二级缓存
步骤:
在hibernate.cfg.xml配置
设置使用二级缓存为true
指定使用哪种二级缓存
别忘了引jar包
指定对哪个domain对象启用二级缓存
测试代码:
public class Test2Cache { public static void main(String[] args) { //第一个session Session session = null; try { session = HibernateUtil.getsession(); User user = (User) session.get(User.class, 2); System.out.println("=========="+user.getUname()); } catch (Exception e) { e.printStackTrace(); } finally { //关闭session,也就意味着一级缓存的结束,来确保之后获取的值是在二级缓存中获取的,而非一级缓存 if (session != null && session.isOpen()) { session.close(); } } System.out.println("------------------------------------"); //第二个session Session session1 = null; try { session1 = HibernateUtil.getsession(); User user = (User) session1.get(User.class, 2); System.out.println("=========="+user.getUname()); } catch (Exception e) { e.printStackTrace(); } finally { if (session1 != null && session1.isOpen()) { session1.close(); } } //完成统计了,在这里测试命中率问题ps:HibernateUtil使自己写的工具类,这里就获取了sessionFactory,也可以直接获取,不写工具类 Statistics statistics = HibernateUtil.getSessionFactory().getStatistics(); System.out.println(statistics);//打印所有信息 //打印具体信息 System.out.println("放入的次数=="+statistics.getSecondLevelCachePutCount()); System.out.println("错过的次数=="+statistics.getSecondLevelCacheMissCount()); System.out.println("命中的次数=="+statistics.getSecondLevelCacheHitCount()); } }
结果:
Hibernate:
select
user0_.uid as uid1_0_,
user0_.uname as uname1_0_,
user0_.pwd as pwd1_0_
from
user user0_
where
user0_.uid=?
==========john
------------------------------------
==========john
Statistics[start time=1450164400227,sessions opened=2,sessions closed=2,transactions=0,successful transactions=0,optimistic lock failures=0,flushes=0,connections obtained=1,statements prepared=1,statements closed=1,second level cache puts=1,second level cache hits=1,second level cache misses=1,entities loaded=1,entities updated=0,entities inserted=0,entities deleted=0,entities fetched=0,collections loaded=0,collections updated=0,collections removed=0,collections recreated=0,collections fetched=0,queries executed to database=0,query cache puts=0,query cache hits=0,query cache misses=0,max query time=0]
放入的次数==1
错过的次数==1
命中的次数==1