`

hernate ehcach usage

阅读更多

1.EhCache是什么
    EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力;

2.EhCache的使用注意点
    当用Hibernate的方式修改表数据(save,update,delete等等),这时EhCache会自动把缓存中关于此表的所有缓存全部删除掉(这样能达到同步)。但对于数据经常修改的表来说,可能就失去缓存的意义了(不能减轻数据库压力);

3.EhCache使用的场合
    3.1比较少更新表数据
        EhCache一般要使用在比较少执行write操作的表(包括update,insert,delete等)[Hibernate的二级缓存也都是这样];
    3.2对并发要求不是很严格的情况
        两台机子中的缓存是不能实时同步的;

4.在项目做的实现
    4.1在工程的src目录下添加ehcache.xml文件,内容如下:
        <?xml version="1.0" encoding="UTF-8"?>
        <ehcache>    
            <diskStore path="java.io.tmpdir" />
          <defaultCache maxElementsInMemory="5"<!--缓存可以存储的总记录量-->
            eternal="false"<!--缓存是否永远不销毁-->
            overflowToDisk="true"<!--当缓存中的数据达到最大值时,是否把缓存数据写入磁盘-->
            timeToIdleSeconds="15"<!--当缓存闲置时间超过该值,则缓存自动销毁-->
                timeToLiveSeconds="120"<!--缓存创建之后,到达该缓存自动销毁-->
          />
        </ehcache>
    4.2在Hibernate.cfg.xml中的mapping标签上面加以下内容:

        <property name="show_sql">true</property>
        <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
        <property name="hibernate.cache.use_query_cache">true</property>
    4.3在要缓存的bean的hbm.xml文件中的class标签下加入以下内容:
       <cache usage="read-only" /><!--也可读写-->
    4.4创建DAO,内容如下:
        Session s = HibernateSessionFactory.getSession();
        Criteria c = s.createCriteria(Xyz.class);
        c.setCacheable(true);//这句必须要有
        System.out.println("第一次读取");
        List l = c.list();
        System.out.println(l.size());
        HibernateSessionFactory.closeSession();

        s = HibernateSessionFactory.getSession();
        c = s.createCriteria(Xyz.class);
        c.setCacheable(true);//这句必须要有
        System.out.println("第二次读取");
        l = c.list();
        System.out.println(l.size());
        HibernateSessionFactory.closeSession();
   4.5这时你会看到打印出来的信息为(表示第二次并没有去读库):
        第一次读取
        Hibernate: *******
        13
        第二次读取
        13

配置Spring+hibernate使用ehcache作为second-level cache

大量数据流动是web应用性能问题常见的原因,而缓存被广泛的用于优化数据库应用。cache被设计为通过保存从数据库里load的数据来减少应用和数据 库之间的数据流动。数据库访问只有当检索的数据不在cache里可用时才必要。hibernate可以用两种不同的对象缓存:first-level cache 和 second-level cache。first-level cache和Session对象关联,而second-level cache是和Session Factory对象关联。

        缺省地,hibernate已经使用基于每个事务的first-level cache。 Hibernate用first-level cache主要是减少在一个事务内的sql查询数量。例如,如果一个对象在同一个事务内被修改多次,hibernate将只生成一个包括所有修改的 UPDATE SQL语句。为了减少数据流动,second-level cache在Session Factory级的不同事务之间保持load的对象,这些对象对整个应用可用,不只是对当前用户正在运行的查询。这样,每次查询将返回已经load在缓存 里的对象,避免一个或更多潜在的数据库事务。

下载ehcache,hibernate3.2必须要ehcache1.2以上才能支持。可以修改log4j配置文件log4j.logger.net.sf.hibernate.cache=debug查看日志

1.在类路径上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 -->
     <diskStore path="java.io.tmpdir"/>


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

         The following attributes are required:

         maxElementsInMemory             - 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.
         overflowToDisk                  - Sets whether elements can overflow to disk when the in-memory cache
                                          has reached the maxInMemory limit.

         The following attributes are optional:
         timeToIdleSeconds               - Sets the time to idle for an element before it expires.
                                          i.e. The maximum amount of time between accesses before an element expires
                                          Is only used if the element is not eternal.
                                          Optional attribute. A value of 0 means that an Element can idle for infinity.
                                          The default value is 0.
         timeToLiveSeconds               - Sets the time to live for an element before it expires.
                                          i.e. The maximum time between creation time and when an element expires.
                                          Is only used if the element is not eternal.
                                          Optional attribute. A value of 0 means that and Element can live for infinity.
                                          The default value is 0.
         diskPersistent                  - Whether the disk store persists between restarts of the Virtual Machine.
                                          The default value is false.
         diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
                                          is 120 seconds.
         -->

     <defaultCache
         maxElementsInMemory="10000"
         eternal="false"
         overflowToDisk="true"
         timeToIdleSeconds="120"
         timeToLiveSeconds="120"
         diskPersistent="false"
         diskExpiryThreadIntervalSeconds="120"/>
        
     <!-- See http://ehcache.sourceforge.net/documentation/#mozTocId258426 for how to configure caching for your objects -->
</ehcache>

2.applicationContext-hibernate.xml里Hibernate SessionFactory配置:

     <!-- Hibernate SessionFactory -->
     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
         <property name="dataSource" ref="dataSource"/>
         <property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property>
         <!-- The property below is commented out b/c it doesn't work when run via
              Ant in Eclipse.   It works fine for individual JUnit tests and in IDEA ??
         <property name="mappingJarLocations">
             <list><value>file:dist/appfuse-dao.jar</value></list>
         </property>
         -->
         <property name="hibernateProperties">
             <props>
                 <prop key="hibernate.dialect">@HIBERNATE-DIALECT@</prop>
                 <!--<prop key="hibernate.show_sql">true</prop>-->
                 <prop key="hibernate.max_fetch_depth">3</prop>
                 <prop key="hibernate.hibernate.use_outer_join">true</prop>
                 <prop key="hibernate.jdbc.batch_size">10</prop>
                 <prop key="hibernate.cache.use_query_cache">true</prop>
                 <prop key="hibernate.cache.use_second_level_cache">true</prop>
                 <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                 <!--
                 <prop key="hibernate.use_sql_comments">false</prop>
                 -->
                 <!-- Create/update the database tables automatically when the JVM starts up
                 <prop key="hibernate.hbm2ddl.auto">update</prop> -->
                 <!-- Turn batching off for better error messages under PostgreSQL
                 <prop key="hibernate.jdbc.batch_size">0</prop> -->
             </props>
         </property>
         <property name="entityInterceptor">
            <ref local="auditLogInterceptor"/>
         </property>
     </bean>
说明:如果不设置“查询缓存”,那么hibernate只会缓存使用load()方法获得的单个持久化对象,如果想缓存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集的话,就需要设置 hibernate.cache.use_query_cache true 才行

3.model类里采用Xdoclet生成*.hbm.xml里的cache xml标签,即<cache usage="read-only"/>

/**
* @hibernate.class table="WF_WORKITEM_HIS"
* @hibernate.cache usage="read-write"
*
*/

4.对于"query cache",需要在程序里编码:

         getHibernateTemplate().setCacheQueries(true);
         return getHibernateTemplate().find(hql);

 

 

使用spring和hibernate配置ehcache和query cache
 
1、applicationContext.xml
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>

这两句加到hibernateProperties中
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
   <ref bean="sessionFactory" />
</property>
<property name="cacheQueries">
   <value>true</value>
</property>
</bean>

添加此bean到applicationcontext.xml中。在各个DAO的bean中,更改如下
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
改为
<property name="hibernateTemplate">
<ref bean="hibernateTemplate" />
</property>

2、ehcache.xml文件放在classes根目录即可

3、pojo与ehcache.xml的配置关系
以com.ce.ceblog.pojos.CeblogJournal为例子
在CeblogJournal.hbm.xml中配置:
<class name="CeblogJournal" table="CEBLOG_JOURNAL" lazy="false">
<cache usage="read-write" region="ehcache.xml中的name的属性值"/>
注意:这一句需要紧跟在class标签下面,其他位置无效。

Ehcache.xml文件主体如下
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="1" timeToLiveSeconds="1" overflowToDisk="true" />
<cache name="com.ce.ceblog.pojos.CeblogJournal" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
hbm文件查找cache方法名的策 略:如果不指定hbm文件中的region="ehcache.xml中的name的属性值",则使用name名为 com.ce.ceblog.pojos.CeblogJournal的cache,如果不存在与类名匹配的cache名称,则用 defaultCache。
如果CeblogJournal包含set集合,则需要另行指定其cache
例如CeblogJournal包含ceblogReplySet集合,则需要
添加如下配置到ehcache.xml中
<cache name="com.ce.ceblog.pojos.CeblogJournal.ceblogReplySet"
maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300"
timeToLiveSeconds="600" overflowToDisk="true" />

另,针对查询缓存的配置如下:
<cache name="org.hibernate.cache.UpdateTimestampsCache"
maxElementsInMemory="5000"
eternal="true"
overflowToDisk="true"/>
<cache name="org.hibernate.cache.StandardQueryCache"
maxElementsInMemory="10000"
eternal="false"
timeToLiveSeconds="120"
overflowToDisk="true"/>

4、选择缓存策略依据:
<cache usage="transactional|read-write|nonstrict-read-write|read-only" />
ehcache不支持transactional,其他三种可以支持。
read- only:无需修改, 那么就可以对其进行只读 缓存,注意,在此策略下,如果直接修改数据库,即使能够看到前台显示效果,但是将对象修改至cache中会报error,cache不会发生作用。另:删 除记录会报错,因为不能在read-only模式的对象从cache中删除。
read-write:需要更新数据,那么使用读/写缓存 比较合适,前提:数据库不可以为serializable transaction isolation level(序列化事务隔离级别)
nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略。

5、调试时候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作过程,主要用于调试过程,实际应用发布时候,请注释掉,以免影响性能。

6、 使用ehcache,打印sql语句是正常的,因为query cache设置为true将会创建两个缓存区域:一个用于保存查询结果集 (org.hibernate.cache.StandardQueryCache); 另一个则用于保存最近查询的一系列表的时间戳(org.hibernate.cache.UpdateTimestampsCache)。请注意:在查询 缓存中,它并不缓存结果集中所包含的实体的确切状态;它只缓存这些实体的标识符属性的值、以及各值类型的结果。需要将打印sql语句与最近的cache内 容相比较,将不同之处修改到cache中,所以查询缓存通常会和二级缓存一起使用。

分享到:
评论

相关推荐

    CSS减肥工具Firefox插件CSS Usage

    标题中的“CSS减肥工具Firefox插件CSS Usage”指的是一个针对Firefox浏览器的扩展,该扩展专门设计用于优化和精简CSS(层叠样式表)代码。CSS是网页设计中用于控制布局和样式的语言,但随着时间的推移,CSS文件可能...

    USB HID USAGE TABLE v1.21最新版

    USB HID Usage Tables v1.21 是一个重要的文档,对于进行USB设备开发,特别是涉及到USB Human Interface Device (HID) 部分的开发者来说,它是不可或缺的参考资源。USB HID是USB设备类别之一,主要用于连接键盘、...

    USB HID USAGE TABLE V1.12--2004.10.28.rar

    USB HID USAGE TABLE V1.12 是一个关于通用串行总线(USB)人机交互设备(Human Interface Device,简称HID)使用的标准文档。这个版本发布于2004年10月28日,提供了对USB HID设备中使用的各种输入、输出和特征报告...

    Firefox_css_usage-0.2.9.zip

    《Firefox CSS Usage插件详解与应用》 在Web开发领域,优化网页性能是至关重要的,而CSS(Cascading Style Sheets)作为控制网页样式的重要工具,其精简和优化直接影响到页面加载速度和用户体验。Firefox的CSS ...

    USB HID USAGE TABLE.pdf

    首先,关于USB HID Usage Tables的版本和修订历史,我们可以看到文档提到了多个版本和修订号,例如版本1.12(rc1修订版,发布于2004年10月28日)和版本1.11(发布于2001年6月27日)。修订号后的日期表示了文档的更新...

    USB HID Usage Tables 1.3

    《USB HID Usage Tables 1.3》是USB Implementers’ Forum发布的一份关于USB设备中人机交互设备(Human Interface Device, HID)使用表的最新版本,涵盖了从1996年到2022年的更新。这份文档是USB设备开发、设计和...

    Android 使用记录访问权限(PACKAGE-USAGE-STATS)、UsageStatsManager

    Android 使用记录访问权限(PACKAGE_USAGE_STATS)、UsageStatsManagerAndroid 使用记录访问权限(PACKAGE_USAGE_STATS)、UsageStatsManagerAndroid 使用记录访问权限(PACKAGE_USAGE_STATS)、...

    HID Usage Tables V1.12

    根据给定文件的信息,我们可以详细地探讨一下USB HID(Human Interface Device)Usage Tables v1.12的相关知识点。 ### HID Usage Tables v1.12概述 HID Usage Tables v1.12是一份关于USB Human Interface Device ...

    Chart-CPUUsage

    标题"Chart-CPUUsage"和描述都指明了我们的主要任务是利用Chart控件来展示计算机CPU的使用情况。 首先,让我们了解`Chart`控件在.NET Framework中的作用。`Chart`控件是ASP.NET Web Forms的一个强大工具,它允许...

    CpuUsage(显示cpu利用动态曲线图)

    《CpuUsage:掌握CPU利用率动态曲线图》 在计算机性能监控中,了解CPU的利用率是至关重要的。CpuUsage工具就是为此目的而设计的,它能够实时地展示CPU利用率的动态曲线图,类似于Windows的任务管理器。这篇文章将...

    usb_Usage_Tables_for_HID_PowerDevices_HID_Usage_Tables_hid_pdf_U

    标题中的“usb_Usage_Tables_for_HID_PowerDevices_HID_Usage_Tables_hid_pdf_U”指的是USB(通用串行总线)设备中HID(Human Interface Device,人机交互设备)使用的表格,特别是关于HID电源设备的使用规范。...

    USB HID usage table

    USB HID usage table USB HID usage table是USB HID开发中必不可少的Usage table,它提供了大量的Usage信息,供HID开发者下载和使用。 标题中的“USB HID usage table”是指该表格提供了USB HID设备的使用情况信息...

    HID usage table

    标题中的“HID usage table”指的是人机交互设备(Human Interface Device)的使用表,这是USB设备类定义中的一部分,特别是在设计和实现USB接口的人体输入设备时非常重要。HID设备包括键盘、鼠标、游戏控制器、触摸...

    Firefox插件 CSS Usage

    css usage是一个基于firebug的firefox扩展,可以用来查看页面中的CSS的使用情况,可以清楚的查看css文件中所有的规则在你的网站中的 真实的使用情况。可以查看一个网站中多个页面中的css使用情况——这个很好,可以...

    CPU Usage 数据记录

    标题中的“CPU Usage 数据记录”指的是一个用于监测和记录计算机CPU使用率的工具。这个工具主要功能是跟踪CPU在一段时间内的工作负载,帮助用户了解系统的性能状况,找出可能的性能瓶颈,或者监控特定进程对CPU资源...

    USB-HID-Usage-Tables.zip_C# HID USB_HID Usage Tables_universal_u

    USB(通用串行总线)HID(Human Interface Device)Usage Tables是USB设备类定义的一部分,主要用于规范人机交互设备的使用方式。在C#编程环境中,与USB HID设备进行通信时,理解这些Usage Tables至关重要。这篇文档...

    usb hid usage报告描述符生成工具

    3. **Usage IDs**:每个报告字段对应一个Usage ID,从usage table中获取,表示该字段的意义和用途。 4. **Data Items**:描述数据字段的大小、排列和编码方式,如Byte、Word、Bit Field等。 5. **Arrays and ...

    CPUUsage.zip_CpuUsage

    标题中的"CPUUsage.zip_CpuUsage"提示我们这是一个与CPU使用率监测相关的程序,很可能是一个VB(Visual Basic)编写的程序。从描述中我们可以推测,这是一段VB源代码,作者鼓励用户亲自尝试并给予支持。 标签"cpu...

    css Usage.zip

    第一步,我们需要安装Firefox,或者确定你...第四步,在浏览器中打开我们要优化的页面(本地的页面也可以),点击右下角的firebug小图标,打开firebug工具窗口,我们会看到在工具选项中我们有一个 CSS Usage工具的按钮。

Global site tag (gtag.js) - Google Analytics