`
macbin
  • 浏览: 8048 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

EhCache使用详细介绍

阅读更多
Ehcache中不仅可以用配置文件来配置缓存,而在代码中也可以实现同样的功能。 

CacheManager singletonManager = CacheManager.create(); 
Cache memoryOnlyCache = new Cache(“testCache”, 50000, false, false, 8, 2); 
Cache test = singletonManager.getCache(“testCache”); 
删除只需要调用singletonManager.removeCache(“testCache”); 
Shotdown CacheManager 
在使用完Ehcache后,必须要shutdown缓存。Ehcache中有自己的关闭机制,不过最好在你的代码中显示调用CacheManager.getInstance().shutdown();

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中,所以查询缓存通常会和二级缓存一起使用。

EhCache使用详细介绍

分享到:
评论

相关推荐

    cache/ehcache缓存使用

    本文将详细讲解"cache/ehcache缓存使用"的相关知识点,包括缓存的基本概念、Ehcache的介绍、以及如何在Java应用中使用Ehcache进行缓存操作。 首先,我们要理解什么是缓存。缓存是一种存储技术,它临时存储常用或...

    ehcache使用,以及集群配置

    本文将详细介绍Ehcache的基本使用和集群配置。 ### Ehcache 基础使用 1. **安装与引入**: 首先,你需要将Ehcache的JAR包添加到你的项目类路径中。你可以通过Maven或Gradle等构建工具进行依赖管理,或者直接下载JAR...

    Ehcache使用

    ### Ehcache 使用详解 #### 一、概述 Ehcache 是一款开源的、纯 Java 缓存...以上是对 Ehcache 使用过程中涉及的主要概念和技术细节的详细介绍。通过合理的配置和使用,Ehcache 可以为应用程序带来显著的性能提升。

    Spring与ehcache结合使用

    本文将详细介绍如何在Spring框架中集成ehcache来实现本地缓存,从而提升应用的整体性能。 #### 二、ehcache简介 ehcache是一款开源的高性能Java本地缓存系统,它可以极大地减少数据库的访问次数,提高应用程序的...

    SpringBoot中Shiro缓存使用Redis、Ehcache的方法

    主要介绍了SpringBoot中Shiro缓存使用Redis、Ehcache的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    ehcache缓存的jar包和配置文件

    下面将详细介绍Ehcache的核心概念、配置以及如何在项目中使用。 1. Ehcache核心概念: - 缓存:缓存是存储临时数据的地方,以便快速检索。Ehcache提供内存和磁盘存储,可以设置不同的缓存策略。 - 缓存管理器...

    EHCache.jar和文档

    在`EHCache 技术文档.pdf`中,你可以找到关于如何安装、配置和使用EHCache的详细指南。这份文档通常包括以下内容: 1. **安装与引入**:讲解如何将EHCache库引入到Java项目中,包括Maven或Gradle的依赖配置。 2. *...

    ehcache知识简介

    本文旨在深入探讨Ehcache的关键特性和实现原理,以便于开发者能够更好地理解和应用这一优秀的缓存技术。 #### 二、特性概览 ##### 1. 快速轻量 - **速度**:经过多次测试证明,Ehcache是最快的Java缓存之一。 - *...

    ehcache资料(个人整理的)

    Ehcache是一款广泛使用的开源Java缓存解决方案,...通过以上对Ehcache的详细介绍,你应该能对这个强大的缓存系统有一个全面的了解。在实际工作中,结合文档和案例,不断实践,才能真正掌握其精髓,提高应用程序的性能。

    springmvc Ehcache

    本文将详细介绍如何将Ehcache集成到Spring MVC应用中,以及如何进行测试和配置。 **一、Ehcache简介** Ehcache是一个开放源代码的、内存级别的、分布式缓存系统。它可以有效地减少数据库负载,提高应用程序的运行...

    Spring+Ehcache集成

    本篇文章将详细介绍如何在Spring项目中集成Ehcache,以及如何通过Spring的AOP(面向切面编程)实现方法级别的缓存注解。 首先,我们需要在项目中引入Ehcache的依赖。通常,这可以通过在`pom.xml`文件中添加Maven...

    Ehcache整合Spring使用页面、对象缓存

    下面将详细介绍Ehcache与Spring的整合及其在页面和对象缓存中的应用。 一、Ehcache简介 Ehcache是基于内存的分布式缓存系统,支持本地缓存、分布式缓存和 terracotta 集群化缓存。它提供了一个简单易用的API,可以...

    ehcache官方教程

    1. **Spring Cache Abstraction**:介绍如何使用 Spring 的缓存抽象层来简化 Ehcache 的集成过程。 2. **注解驱动**:使用注解来标记需要缓存的方法。 3. **配置管理**:通过 Spring 的配置文件或 Java 配置类来管理...

    Ehcache远程复制

    尽管由于OCR扫描技术的原因,部分内容存在识别错误或遗漏,但大致可推断手册详细介绍了Ehcache集群配置的关键步骤和方法,包括如何在不同节点之间同步缓存数据,以及如何进行故障转移等高级特性,这些配置对于确保...

    ehcache 测试demo

    本篇将基于提供的"ehcache_test"压缩包文件,详细介绍如何在Java项目中进行Ehcache的配置和使用。 1. **Ehcache简介** Ehcache是一个高性能、轻量级的缓存解决方案,支持本地内存缓存和分布式缓存。它可以被集成到...

    ehcache-2.7.3-distribution.tar.gz

    2. "EHCache技术文档详解.doc":如前文描述,这份文档提供了EHCache的详细技术信息,包括配置、API使用、最佳实践等,是学习和使用EHCache的重要参考资料。 3. "ehcache-2.7.3-distribution.tar.gz":这是原始的...

    Java流行ehcache缓存

    本文将详细介绍Ehcache的基础知识、配置以及如何在实际项目中应用。 1. **Ehcache基本概念** - **缓存**:缓存是一种存储机制,用于暂时保存数据,以便快速访问。它减少了对数据库或其他慢速资源的调用,提高了...

    ehcache-clustered-3.3.1-kit.zip

    3. API文档:`ehcache-api-docs`可能包含Ehcache的API文档,这些文档详细介绍了如何使用Ehcache API来创建、配置和操作缓存。 4. 参考文档:`ehcache-reference-guide`可能包含Ehcache的官方参考指南,涵盖了各种...

    spring+ibatis+ehcache整合例子

    下面将详细介绍这三个框架及其整合的关键点。 **Spring框架** Spring是一个全面的企业级应用开发框架,它提供了一个容器来管理对象的生命周期和依赖关系,以及AOP(面向切面编程)功能。在本项目中,Spring作为核心...

    SpringBoot 集成Ehcache实现缓存

    下面将详细介绍如何在一个Spring Boot项目中集成并使用Ehcache缓存。 ##### 1. 创建项目 首先,使用IDEA创建一个Maven类型的Spring Boot项目。确保项目结构符合Spring Boot的标准。 ##### 2. 数据库初始化 为了...

Global site tag (gtag.js) - Google Analytics