1、前言
这篇博客是在前几篇博客的基础上讲解的。hibernate的二级缓存是属于sessionFactory级别的缓存,第一级的缓存是属于session级别的缓存,是属于事务范围的缓存,由Hibernate管理,一般无需进行干预。第二级别的缓存是SessionFactory级别的缓存,是属于进程范围的缓存。
2、hibernate的二级缓存
1.分类
二级缓存也分为了两种
内置缓存:Hibernate自带的,不可卸载,通常在Hibernate的初始化阶段,Hibernate会把映射元数据和预定义的SQL语句放置到 SessionFactory的缓存中。该内置缓存是只读的。
外置缓存:通常说的二级缓存也就是外置缓存,在默认情况下SessionFactory不会启用这个缓存插件,外置缓存中的数据是数 据库数据的复制,外置缓存的物理介质可以是内存或者硬盘。
2、并发访问策略
transactional (事务型) | 仅在受管理的环境中适用 提供Repeatable Read事务隔离级别 适用经常被读,很少修改的数据 可以防止脏读和不可重复读的并发问题 缓存支持事务,发生异常的时候,缓存也能够回滚 |
read-write (读写型) | 提供Read Committed事务隔离级别 在非集群的环境中适用 适用经常被读,很少修改的数据 可以防止脏读 更新缓存的时候会锁定缓存中的数据 |
nonstrict-read-write (非严格读写型) | 适用极少被修改,偶尔允许脏读的数据(两个事务同时修改数据的情况很少见) 不保证缓存和数据库中数据的一致性 为缓存数据设置很短的过期时间,从而尽量避免脏读 不锁定缓存中的数据 |
read-only (只读型) | 适用从来不会被修改的数据(如参考数据) 在此模式下,如果对数据进行更新操作,会有异常 事务隔离级别低,并发性能高 在集群环境中也能完美运作 |
通过上图的分析,
适合放到二级缓存的数据:
很少被修改或根本不改的数据 数据字典(如下拉框0代表唱歌,1代表跳舞);
不是很重要的数据,允许出现偶尔的并发问题
不适合放到二级缓存的数据:
经常被修改
财务数据,绝对不允许出现并发问题
与其他应用数据共享的数据
3、二级缓存的配置
1、hibernate支持的缓存插件
ehcache:
是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大。
可作为进程范围内的缓存,存放数据的物理介质可以是内存或硬盘,对Hibernate的查询缓存提供了支持
OpenSymphony:
可作为进程范围内的缓存,存放数据的物理介质可以是内存或硬盘,提供了丰富的缓存数据过期策略,对Hibernate的查询缓存提供了支持
SwarmCache:可作为集群范围内的缓存,但不支持Hibernate的查询缓存
JBossCache:可作为集群范围内的缓存,支持Hibernate的查询缓存
2、学习了ehcache缓存,以ehcache为例讲解二级缓存
2.1在pom.xml中导入相关依赖
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>
2.2 src/main/resource添加ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
<!--path:指定在硬盘上存储对象的路径-->
<!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));-->
<diskStore path="C:\Users\ASUS\AppData\Local\Temp2"/>
<!--defaultCache:默认的管理策略-->
<!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
<!--maxElementsInMemory:在内存中缓存的element的最大数目-->
<!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
<!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
<!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
<!--FIFO:first in first out (先进先出)-->
<!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
<!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
<defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
<!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
<cache name="com.zking.one.entity.User" eternal="false" maxElementsInMemory="1"
overflowToDisk="true" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>
2.3 hibernate.cfg.xml中添加二级缓存相关配置
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- EhCache驱动 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
2.4 指定实体类开启二级缓存
<!-- 注解式开发 -->
<class-cache usage="read-write" class="entity.Dict"/>
<!-- xml配置方式 -->
<class table="t_sys_dict" name="entity.Dict">
<cache usage="read-write"/>
.......
</class>
4.Test测试
package com.aa.eight.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.aa.eight.util.EhcacheUtil;
import com.aa.one.entity.User;
import com.aa.two.util.SessionFactoryUtils;
public class EhcacheTest3 {
/**
* hibernate整合ehcache完成查询单个用户
* @param args
*/
public static void main(String[] args) {
Session session = SessionFactoryUtils.getSession();
Transaction transaction = session.beginTransaction();
User user = session.get(User.class, 2);
System.err.println(user);
User user2 = session.get(User.class, 2);
System.err.println(user2);
User user3 = session.get(User.class, 2);
System.err.println(user3);
transaction.commit();
session.close();
}
}
注1:查全部需要编写代码来开启二级缓存的
query.setCacheRegion("entity.Dict");//指定缓存策略,名字必须实体类的完整类名
query.setCacheable(true);//手动开启二级缓存
这是添加了一个字段
private boolean userCache = false; public void setUserCache(boolean userCache) { |
package com.aa.eight.test;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import com.aa.eight.util.EhcacheUtil;
import com.aa.one.entity.User;
import com.aa.two.util.SessionFactoryUtils;
public class EhcacheTest4 {
/**
* hibernate整合ehcache完成查询多个用户
* ehcache查询多个不会用到缓存
* @param args
*/
public static void main(String[] args) {
Session session = SessionFactoryUtils.getSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("from User");
User user = new User();
user.setUserCache(true);
/**
* 使用dao方法的时候,使用ehcache缓存,默认查多条记录是不是要缓存的
*/
if(user.isUserCache()) {
query.setCacheable(true);//设置缓存
}
List list = query.list();
System.err.println(list.size());
List list2 = query.list();
System.err.println(list2.size());
List list3 = query.list();
System.err.println(list3.size());
transaction.commit();
session.close();
}
}