`
guyinglong
  • 浏览: 73937 次
  • 性别: Icon_minigender_1
  • 来自: 江西
社区版块
存档分类
最新评论

ehcache-----在spring和hibernate下管理ehcache和query cache

阅读更多
1. 在Hibernate配置文件中设置:
     <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingResources">
        <list>
            <value>com/ouou/model/Videos.hbm.xml</value>  
         </list>
         </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
                <prop key="hibernate.query.substitutions">true 'Y', false 'N'</prop>
                <!--add ehcache-->
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                <prop key="hibernate.cache.use_query_cache">false</prop><!-- 是否使用查询缓存 -->
                <!--
                <prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml</prop>
                <prop key="hibernate.show_sql">true</prop>
                -->
                <!--<prop key="hibernate.transaction.auto_close_session">true</prop>-->
                <prop key="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</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">25</prop>
                <!--
                <prop key="hibernate.connection.pool_size">10</prop>
                -->
            </props>
        </property>
    </bean>
    如果不设置“查询缓存”,那么hibernate只会缓存使用load()方法获得的单个持久化对象,如果想缓存使用findall()、 list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集的话,就需要设置hibernate.cache.use_query_cache true 才行

2.首先设置EhCache,建立配置文件ehcache.xml,默认的位置在class-path,可以放到你的src目录下:
<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"/>-->
     <diskStore path="/data/ehcache"/>

    <!--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"/>
    <cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="5000"
     eternal="true" overflowToDisk="true"/>
    <cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="5" eternal="false"
    timeToLiveSeconds="120" overflowToDisk="true"/>
    <cache name="userCache" maxElementsInMemory="100000" eternal="false" timeToIdleSeconds=
        "600"    timeToLiveSeconds="600" overflowToDisk="false" diskPersistent="false"/>
    <cache name="com.ouou.webapp.util.OuouMethodIntecepter" maxElementsInMemory="100000"
    eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="600" overflowToDisk="false"
    diskPersistent="false"/>
    <cache name="bbcode" maxElementsInMemory="100000" eternal="false" timeToIdleSeconds="600"
    timeToLiveSeconds="600"
    overflowToDisk="false" diskPersistent="false"/>
    <cache name="com.ouou.model.Videos" maxElementsInMemory="10000"  eternal="false"
    overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskPersistent="false"/>
    <cache name="com.ouou.model.Tags" maxElementsInMemory="10000"  eternal="false"
    overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskPersistent="false"/>
</ehcache>
以com.ouou.model.Videos为例子
在Videos.hbm.xml中配置:
<class name="Videos" table="TEST" lazy="false">
  <cache usage="read-write" region="ehcache.xml中的name的属性值"/>注意:这一句需要紧跟在class标签下面,其他位置无效。
hbm文件查找cache方法名的策略:如果不指定hbm文件中的region="ehcache.xml中的name的属性值",则使用name名为com.ouou.model.Videos的cache,
如果不存在与类名匹配的cache名称,则用defaultCache。
如果Videos包含set集合,则需要另行指定其cache
例如Videos包含Tags集合,则需要
添加如下配置到ehcache.xml中
<cache name="com.ouou.model.Tags"
        maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120"
        timeToLiveSeconds="120" overflowToDisk="false" />
另,针对查询缓存的配置如下:
<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"/>

3、 选择缓存策略依据:

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

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

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

英文参考资料:http://ehcache.sourceforge.net/documentation/#mozTocId258426
博文参考:http://blog.csdn.net/yun15291li/archive/2006/02/21/604095.aspx
                 http://zyl.iteye.com/blog/68369
其他:http://dev.yesky.com/157/2557157.shtml

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/houhy/archive/2007/09/28/1805017.aspx
分享到:
评论

相关推荐

    spring hibernate cache

    Spring Cache 是 Spring 为整个应用提供的缓存抽象层,它支持多种缓存实现,包括 EhCache 和 Hibernate 的二级缓存。通过在方法上添加 @Cacheable、@CacheEvict 等注解,可以在方法调用前后自动完成缓存的存取和清理...

    详解spring boot集成ehcache 2.x 用于hibernate二级缓存

    本篇文章主要介绍了如何在 Spring Boot 中集成 Ehcache 2.x 作为 Hibernate 的二级缓存,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。 Ehcache 简介 Ehcache 是一个纯 Java 的缓存框架,既可以当做一个...

    Spring 整合 Hibernate 时启用二级缓存实例详解

    Spring 整合 Hibernate 时启用二级缓存实例详解 写在前面:  1. 本例使用 Hibernate3 + Spring3;  2.... 1. 导入 ehcache-x.x.x.jar 包;...&lt;prop key=hibernate.cache.use_query_cache&gt;true &lt;!-

    EHcache 缓存使用 手动存储 配置到SSH

    在SSH架构中,我们可以分别在Struts、Spring和Hibernate三个层次上配置和使用EHcache。首先是**Spring**,作为整个应用的容器,它负责管理包括缓存管理器在内的各种bean。在`applicationContext.xml`配置文件中,...

    Hibernate-开发指南.pdf

    - Spring提供了对Hibernate的支持,简化了事务管理和DAO层的开发。 - **Spring配置**: - 定义`SessionFactory` bean。 - 使用`TransactionManager`管理事务。 - **示例配置**: ```xml ...

    hibernate配置二三级缓存

    在项目的`src/main/resources`目录下创建`ehcache.xml`文件来配置EhCache的具体参数。 ```xml &lt;ehcache&gt; &lt;diskStore path="java.io.tmpdir/ehcache"/&gt; timeToLiveSeconds="120" overflowToDisk="true" ...

    HIBERNATE4开发文档,HIBERNATE4的变化

    在Hibernate4的开发中,相较于之前的版本,存在一些显著的变化,这些变化主要集中在session管理、事务处理、缓存配置以及与Spring框架的集成等方面。以下将详细解释这些关键点: 1. **Spring3.1与Hibernate4的整合*...

    hibernate二级缓存 SSH

    Spring框架则提供了依赖注入和事务管理,以及与各种持久化层(如Hibernate)的集成。Hibernate是对象关系映射(ORM)工具,它允许开发者用面向对象的方式来操作数据库。 在Hibernate中,一级缓存是指SessionFactory...

    Hibernate二级缓存技术

    &lt;property name="hibernate.cache.use_query_cache"&gt;true ``` 同时,在Spring的配置文件中创建Hibernate的`SessionFactory`,并设置相关属性: ```xml &lt;!– 配置Hibernate SessionFactory –&gt; ...

    spring教程

    Spring通过HibernateTemplate或SessionFactoryBean支持Hibernate,使得在Spring应用中使用Hibernate变得简单,同时保持了Spring的事务管理和依赖注入优势。 Spring还提供了缓存支持,通过Spring Cache抽象,可以...

    hibernate包

    10. **依赖管理**:在实际项目中,还需要管理其他依赖,如Spring框架与Hibernate的集成,如spring-orm.jar,用于配置和管理SessionFactory。 在开发时,将这些库集成到项目中,可以快速搭建起与数据库交互的ORM层。...

    Hibernate二级缓存+分页功能

    在Java的持久化框架Hibernate中,二级缓存和分页功能是两个重要的优化手段,能够显著提升应用程序的性能和用户体验。下面将详细讲解这两个概念及其实际应用。 **一、Hibernate二级缓存** Hibernate一级缓存是指...

    spring框架笔记

    4. **Hibernate缓存配置**:在Hibernate中,可以启用二级缓存,通过`hibernate.cache.provider_class`配置EhCache提供者,以及开启查询缓存`hibernate.cache.use_query_cache`。这样,查询结果可以被缓存,减少...

    hibernate3 中文API

    9. **事务管理(Transaction Management)**: Hibernate支持编程式和声明式事务管理。编程式事务管理通过Session的beginTransaction()、commit()和rollback()方法手动控制;声明式事务管理通常结合Spring等框架实现...

    Hibernate连接数据库的注册的项目

    &lt;property name="hibernate.cache.region.factory_class"&gt;org.hibernate.cache.ehcache.EhCacheRegionFactory ``` 最后,别忘了关闭SessionFactory,避免资源泄露: ```java if (sessionFactory != null) { ...

    Hibernate_API_zh-cn高手汇总

    5. Criteria和Query:提供强大的查询机制,Criteria用于构建动态查询,HQL(Hibernate Query Language)则是一种面向对象的查询语言。 三、对象持久化 Hibernate提供了四种对象持久化的方式: 1. Save():临时对象...

    Hibernate环境搭建的包和API中文版

    在实际开发中,结合IoC(Inversion of Control,如Spring框架)可以更好地管理和使用Hibernate,避免资源泄露,提高代码的可测试性和可维护性。 总之,Hibernate环境的搭建涉及到JDBC驱动的集成、配置文件的编写、...

    SSH所用JAR包详解.docx

    SSH(Struts、Spring、Hibernate)是一个流行的Java Web开发框架,它将模型、视图和控制器(MVC)模式紧密集成,提供了强大的企业级应用开发能力。SSH框架中涉及的JAR包是其正常运行的基础,下面将详细介绍SSH框架所...

Global site tag (gtag.js) - Google Analytics