码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate之二级缓存

时间:2014-12-03 23:00:07      阅读:327      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   使用   

Hibernate缓存
  缓存(Cache):计算机领域非常通用的概念。它介于应用程序和永久性数据存储源(如硬盘上的文件或数据库)之间,其作用是降低应用程序直接读写永久性数据存储源的频率,从而提高应用的运行性能。缓存中的数据时数据存储源中数据的拷贝。缓存的物理介质通常是内存

Hibernate中提供了两个级别的缓存
  第一级别的缓存是Session级别的缓存,它是属于事务范围的缓存。这一级别的缓存有Hibernate管理的
  第二级别的缓存是SessionFactory级别的缓存,它是属于进程范围的缓存

SessionFactory级别的缓存
  SessionFactory的缓存可以分为两类:
    内置缓存:Hibernate自带的,不可卸载。通常在Hibernate的初始化阶段,Hibernate会把映射元数据和预定义的SQL语句放到SessionFactory的缓存中,映射元数据是映射文件中数据(.hbm.xml文件中的数据)的复制。该内置缓存是只读的。
    外置缓存(二级缓存):一个可配置的缓存插件。在默认情况下,SessionFactory不会启用这个缓存插件。外置缓存中的数据是数据库数据的复制,外置缓存的物理介质可以是内存或硬盘


使用Hibernate的二级缓存
  适合放入二级缓存中的数据:
    很少被修改
    不是很重要的数据,允许出现偶尔的并发问题
  不适合放入二级缓存中的数据:
    经常被修改
    财务数据,绝对不允许出现并发问题
    与其他应用程序共享的数据


Hibernate二级缓存的架构

bubuko.com,布布扣

 

二级缓存的并发访问策略
  两个并发的事务同时访问持久层的缓存的相同的数据时,也有可能出现各类并发问题
  二级缓存可以设定一下4种类型的并发访问策略,每一种访问策略对应一种事务隔离级别
    非严格读写(Nonstrict-read-write):不保证缓存与数据库中数据的一致性,提高Read Uncommited事务隔离级别,对于极少被修改,而且允许脏读的数据,可以采用这种策略
    读写型(Read-write):提供Read Commited数据隔离级别。对于经常脏读但是很少被修改的数据,可以采用这种隔离类型,因为它可以防止脏读
    事务型(Transaction):仅在受管理环境下适用。它提供了Repeatable Read事务隔离级别。对于经常读但是很少被修改的数据,可以采用这种隔离类型。因为它可以防止脏读和不可重复读
    只读型(Read-only):提供Serializable数据隔离级别。对于从来不会被修改的数据,可以采用这种访问策略

 

管理Hibernate的二级缓存
  Hibernate的二级缓存时进程或集群范围内的缓存
  二级缓存是可配置的插件,Hibernate允许选用以下类型的缓存插件:
    EHCache:可作为进程范围内的缓存,存放数据的物理介质可以使用内存或硬盘,对Hibernate的查询缓存提供了支持
    OpenSymphony OSCache:可作为进程范围内的缓存,存放数据的物理介质可以使用内存或硬盘,提供了丰富的缓存数据过期策略,对Hibernate的查询缓存提供了支持
    SwarmCache:可作为集群范围内的缓存,但不支持Hibernate的查询缓存
    JBossCache:可作为集群范围内的缓存,支持Hibernate的查询缓存
4中缓存插件的并发访问策略(X代表支持,空白代表不支持)

  Read-only Nonstrict-read-write Read-write Transaction
EHCache X X X  
OpenSymphony OSCache X X X  
SwarmCache X X    
JBossCache X     X

 

配置进程范围内的二级缓存
  配置进程范围内的二级缓存的步骤:
    选择合适的缓存插件:EHCache(jar包和配置文件),并修改配置文件-----(hibernate-release-4.3.7.Final\lib\optional\ehcache\*.jar和hibernate-release-4.3.7.Final\project\etc\ehcache.xml)
    在Hibernate的配置文件中启用二级缓存并指定和EHCache对应的缓存适配器
    选择需要使用二级缓存的持久化类,设置它的二级缓存的并发访问策略
      <class>元素的cache子元素表明Hibernate会缓存对象的简单属性,但不会缓存集合属性,若希望缓存集合属性中的元素,必须在<set>元素中加入<cache>子元素
      在Hibernate配置文件中通过<class-cache/>节点配置使用缓存

==================本次介绍以EHCache为例==================================

EHCache配置文件(ehcache.xml)介绍

  <diskStore>:指定一个目录,当EHCache把数据写到硬盘上时,将把数据写到这个目录下
  <defaultCache>:设置缓存的默认数据过期策略
  <cache>:设定具体的命名缓存的数据过期策略。每个命名缓存代表一个缓存区域
  缓存区域(region):一个具有名称的缓存块,可以给每一个缓存块设置不同的缓存策略。如果没有设置任何的缓存区域,则所有被缓存的对象,都将使用默认的缓存策略。即:<defaultCache.../>
  Hibernate在不同的缓存区域保存不同的类/集合
    对于类而言,区域的名称是类名。如:com.yl.domain.Customer
    对于集合而言,区域的名称是类名加属性名。如:com.yl.domain.Customer.orders
  cache元素的属性
    name:设置缓存的名字,它的取值为类的全限定名或类的集合的名字
    maxInMemory:设置基于内存的缓存中可存放的对象最大数目
    eternal:设置对象是否为永久的,true表示永不过期,此时将忽略timeToIdleSeconds和timeToLiveSeconds属性;默认值是false
    timeToIdleSeconds:设置对象空闲最长时间,以秒为单位,超过这个时间,对象过期,当对象过期时,EHCache会把它从缓存中清除。如果此值为0,表示对象可以无限期地处于空闲状态
    timeToLiveSeconds:设置对象生存最长时间,超过这个时间,对象过期。如果此值为0,表示对象可以无限期地存在于缓存中。该属性值必须大于或等于timeToIdleSeconds属性值
    overflowToDisk:设置基于内在的缓存中的对象数目达到上线后,是否把溢出的对象写到基于硬盘的缓存中

 

查询缓存
  对于经常使用的查询语句,使用启用了查询缓存,当第一次执行查询语句时,Hibernate会把查询结果存放在查询缓存中。以后再次执行该查询语句时,只需从缓存中获得查询结果,从而提高查询性能
  查询缓存使用于如下场合:
    应用程序运行时经常使用查询语句
    很少对于查询语句检索到的数据进行插入、删除和更新操作
  启用查询缓存的步骤:
    配置二级缓存,因为查询缓存依赖于二级缓存
    在Hibernate配置文件中启用查询缓存
    对于希望启用查询换的查询语句,调用Query的setCacheable()方法

时间戳缓存区域
  时间戳缓存区域存放了对于查询结果相关的表进行插入,更新或删除操作的时间戳。Hibernate通过时间戳缓存区域来判断被缓存的查询结果是否过期,其运行过程如下:
    T1时刻执行查询操作,把查询结果存放在QueryCache区域,记录该区域的时间戳为T1
    T2时刻对查询结果相关的表进行更新操作,Hibernate把T2时刻存放在UpdateTimestampCache区域
    T3时刻执行查询结果前,先比较QueryCache区域的时间戳和UpdateTimestampCache区域的时间戳,若T2>T1,那么久丢弃原先存放在QueryCache区域的查询结果,更新到数据库中查询数据,再把结果存放到QueryCache区域;若T2<T1,直接从QueryCache中获取查询结果

Query接口的iterate()方法
  同list()一样也能执行查询操作
  list()方法执行的SQL语句包含实体类对应的数据表的所有字段
  iterate()方法执行的SQL语句中仅包含实体类对应的数据表的ID字段
  当遍历访问结果集时,该方法先到Session缓存及二级缓存中查询是否存在特定OID的对象,如果存在,就直接返回该对象,如果不存在,该对象就通过相应的SQL SELECT语句到数据库中加载特定的实体对象

大多数情况下,应考虑使用list()方法执行查询操作。iterate()犯法仅在满足一下条件的场合,可以稍微提高查询性能:
要查询的数据表中包含大量的字段
启用了二级缓存,且二级缓存中可能已经包含了待查询的对象

 

============================代码说明==============================

hibernate.cfg.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <!-- 配置连接数据库的基本信息 -->
 8         <property name="connection.username">scott</property>
 9         <property name="connection.password">tiger</property>
10         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
11         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
12     
13         <!-- 配置hibernate基本信息 -->
14         <!-- hibernate所使用的数据库方言 -->
15         <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
16         
17         <!-- 执行操作时是否在控制台打印sql -->
18         <property name="show_sql">true</property>
19         
20         <!-- 是否对SQL进行格式化 -->        
21         <property name="format_sql">true</property>
22         
23         <!-- 指定自动生成数据表的策略 -->
24         <property name="hbm2ddl.auto">update</property>
25         
26         <!-- 设置Hibernate 的事务的隔离级别 -->
27         <property name="connection.isolation">2</property>
28         
29         <!-- 删除对象后,使其OID置为null -->
30         <property name="hibernate.use_identifier_rollback">true</property>
31         
32         <!-- 配置C3P0数据源 -->
33         <!-- 
34         <property name="hibernate.c3p0.max_size">10</property>
35         <property name="hibernate.c3p0.min_size">5</property>
36         <property name="c3p0.acquire_increment">2</property>
37          
38         <property name="c3p0.idle_test_period">2000</property>
39         <property name="c3p0.timeout">2000</property>
40         
41         <property name="c3p0.max_statements">10</property>
42          -->
43          
44         <!-- 设定JDBC的Statement 读取数据的时候每次从数据库中取出的数据条数 -->
45         <property name="hibernate.jdbc.fetch_size">100</property>
46          
47         <!-- 设定对数据库进行批量删除、批量更新和批量插入的时候的批次的大小 -->
48         <property name="hibernate.jdbc.batch_size">30</property>
49         
50         <!-- 启用二级缓存 -->
51         <property name="cache.use_second_level_cache">true</property>
52         
53         <!-- 配置使用的二级缓存的产品 -->
54         <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
55         
56         <!-- 配置启用查询缓存 -->
57         <property name="cache.use_query_cache">true</property>
58         
59         <!-- 指定关联的.hbm.xml 文件 -->
60         <mapping resource="com/yl/hibernate/entities/Department.hbm.xml"/>
61         <mapping resource="com/yl/hibernate/entities/Employee.hbm.xml"/>
62         
63         <class-cache usage="read-write" class="com.yl.hibernate.entities.Employee"/>
64         
65         <class-cache usage="read-only" class="com.yl.hibernate.entities.Department"/>
66         <collection-cache usage="read-only" collection="com.yl.hibernate.entities.Department.emps"/>
67 
68     </session-factory>
69 </hibernate-configuration>

ehcache.xml

<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User‘s home directory
         user.dir - User‘s current working directory
         java.io.tmpdir - Default temp file path -->
    <!-- 
        指定一个目录,当EHCache 把数据写到硬盘上时,将把数据写到这个目录下
     -->
    <!-- <diskStore path="java.io.tmpdir"/> -->
    <diskStore path="D:\\tmpdir"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
    <!-- 
        设置缓存的默认数据过期策略
     -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts

        The following attributes are required for defaultCache:

        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->

    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
    <!-- 
        设定具体的命名缓存的数据过期策略。每个命名缓存代表一个缓存区域
        缓存区域(region):一个具有名称的缓存块,可以给每一个缓存块设置不同的缓存策略。
        如果没有设置任何的缓存区域,则所有被缓存的对象,都将使用默认的缓存策略。即:<defaultCache.../>
        
        Hibernate在不同的缓存区域保存不同的类/集合
            对于类而言,区域的名称是类名。如:com.yl.domain.Customer
            对于集合而言,区域的名称是类名加属性名。如:com.yl.domain.Customer.orders
     -->
     <!-- 
         name:设置缓存的名字,它的取值为类的全限定名或类的集合的名字
        maxInMemory:设置基于内存的缓存中可存放的对象最大数目
        eternal:设置对象是否为永久的,true表示永不过期,此时将忽略timeToIdleSeconds和timeToLiveSeconds属性;默认值是false
        timeToIdleSeconds:设置对象空闲最长时间,以秒为单位,超过这个时间,对象过期,当对象过期时,EHCache会把它从缓存中清除。如果此值为0,表示对象可以无限期地处于空闲状态
        timeToLiveSeconds:设置对象生存最长时间,超过这个时间,对象过期。如果此值为0,表示对象可以无限期地存在于缓存中。该属性值必须大于或等于timeToIdleSeconds属性值
        overflowToDisk:设置基于内在的缓存中的对象数目达到上线后,是否把溢出的对象写到基于硬盘的缓存中
      -->
    <cache name="com.yl.hibernate.entities.Employee"
        maxElementsInMemory="1"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="com.yl.hibernate.entities.Department.emps"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->

    <!-- Place configuration for your caches following -->

</ehcache>

测试类:

  1 package com.yl.hibernate.test;
  2 
  3 
  4 import java.util.ArrayList;
  5 import java.util.Arrays;
  6 import java.util.Iterator;
  7 import java.util.LinkedHashSet;
  8 import java.util.List;
  9 import java.util.Set;
 10 
 11 import oracle.net.aso.e;
 12 
 13 import org.hibernate.Criteria;
 14 import org.hibernate.Query;
 15 import org.hibernate.Session;
 16 import org.hibernate.SessionFactory;
 17 import org.hibernate.Transaction;
 18 import org.hibernate.cfg.Configuration;
 19 import org.hibernate.criterion.Conjunction;
 20 import org.hibernate.criterion.Disjunction;
 21 import org.hibernate.criterion.MatchMode;
 22 import org.hibernate.criterion.Order;
 23 import org.hibernate.criterion.Projection;
 24 import org.hibernate.criterion.Projections;
 25 import org.hibernate.criterion.Restrictions;
 26 import org.hibernate.service.ServiceRegistry;
 27 import org.hibernate.service.ServiceRegistryBuilder;
 28 import org.junit.After;
 29 import org.junit.Before;
 30 import org.junit.Test;
 31 
 32 import com.yl.hibernate.entities.Department;
 33 import com.yl.hibernate.entities.Employee;
 34 
 35 public class HibernateTest {
 36 
 37     private SessionFactory sessionFactory;
 38     private Session session;
 39     private Transaction transaction;
 40     
 41     @Before
 42     public void init() {
 43         Configuration configuration = new Configuration().configure();
 44         ServiceRegistry serviceRegistry = 
 45                 new ServiceRegistryBuilder().applySettings(configuration.getProperties())
 46                                             .buildServiceRegistry();
 47 
 48         sessionFactory = configuration.buildSessionFactory(serviceRegistry);
 49         
 50         session = sessionFactory.openSession();
 51 
 52         transaction = session.beginTransaction();
 53     }
 54     @After
 55     public void destory() {
 56         transaction.commit();
 57         
 58         session.close();
 59         
 60         sessionFactory.close();
 61     }
 62 
 63     
 64     @Test
 65     public void testHibernateSecondLevelCache() {
 66         Employee employee = (Employee) session.get(Employee.class, 7369);
 67         System.out.println(employee.getName());
 68         
 69         transaction.commit();
 70         session.close();
 71         
 72         session = sessionFactory.openSession();
 73         transaction = session.beginTransaction();
 74         
 75         Employee employee2 = (Employee) session.get(Employee.class, 7369);
 76         System.out.println(employee2.getName());
 77         
 78     }
 79     
 80     @Test
 81     public void testCollectionSecondLevelCache() {
 82         Department dept = (Department) session.get(Department.class, 20);
 83         System.out.println(dept.getName());
 84         System.out.println(dept.getEmps().size());
 85         
 86         transaction.commit();
 87         session.close();
 88         
 89         session = sessionFactory.openSession();
 90         transaction = session.beginTransaction();
 91         
 92         Department dept2 = (Department) session.get(Department.class, 20);
 93         System.out.println(dept2.getName());
 94         System.out.println(dept2.getEmps().size());
 95     }
 96     
 97     /**
 98      * 查询缓存依赖于二级缓存
 99      */
100     @Test
101     public void TestQueryCache() {
102         Query query = session.createQuery("FROM Employee");
103         query.setCacheable(true);
104         
105         List<Employee> emps = query.list();
106         System.out.println(emps.size());
107         
108         emps = query.list();
109         System.out.println(emps.size());
110         
111         Criteria criteria = session.createCriteria(Employee.class);
112         criteria.setCacheable(true);
113     }
114     
115     @Test
116     public void testUpdateTimestampCache() {
117         Query query = session.createQuery("FROM Employee");
118         query.setCacheable(true);
119         
120         List<Employee> emps = query.list();
121         System.out.println(emps.size());
122         
123         Employee employee = (Employee) session.get(Employee.class, 7839);
124         employee.setSalary(15000F);
125         
126         emps = query.list();
127         System.out.println(emps.size());
128     }
129     
130     @Test
131     public void testQueryIterate() {
132         Department dept = (Department) session.get(Department.class, 20);
133         System.out.println(dept.getName());
134         System.out.println(dept.getEmps().size());
135         
136         Query query = session.createQuery("FROM Employee e WHERE e.dept.id = 20");
137         /*List<Employee> emps = query.list();
138         System.out.println(emps.size());*/
139         
140         Iterator<Employee> empIt = query.iterate();
141         while (empIt.hasNext()) {
142             System.out.println(empIt.next().getName());
143         }
144         
145     }
146     
147     
148     
149 }

 

Hibernate之二级缓存

标签:des   style   blog   http   io   ar   color   os   使用   

原文地址:http://www.cnblogs.com/dreamfree/p/4141448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!