`

Hibernate二级缓存配置之EhCache

阅读更多

1、hibernate.cfg.xml中添加:

 

  <!-- 开启二级缓存 -->
 <property name="hibernate.cache.use_second_level_cache">
  true
 </property>
 <!-- 指定缓存产品提供商 -->
 <property name="hibernate.cache.provider_class">
  org.hibernate.cache.EhCacheProvider
 </property>

 

2、在src下新建一个ehcache.xml文件内容如下:

<ehcache>
    <diskStore path=”D:\cache”/>
    <defaultCache  maxElementsInMemory=”1000″ eternal=”false” overflowToDisk=”true”
        timeToIdleSeconds=”120″
        timeToLiveSeconds=”180″
        diskPersistent=”false”
        diskExpiryThreadIntervalSeconds=”60″/>
 <cache name=”cn.itcast.bean.Person” maxElementsInMemory=”100″ eternal=”false”
    overflowToDisk=”true” timeToIdleSeconds=”300″ timeToLiveSeconds=”600″ diskPersistent=”false”/>
</ehcache>

 上述属性介绍如下:

       1、defaultCache节点为缺省的缓存策略
       2、maxElementsInMemory 内存中最大允许存在的对象数量
       3、eternal 设置缓存中的对象是否永远不过期
      4、overflowToDisk 把溢出的对象存放到硬盘上
      5、timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉
      6、timeToLiveSeconds 指定缓存对象总的存活时间
      7、diskPersistent 当jvm结束是是否持久化对象
      8、diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间

 

 

3、指定需要为哪些类添加二级缓存,有两种方式:

    第一种:在与pojo相关联的xxxx.hbm.xml 文件里添加:

               <class-cache class="com.lring.pojo.Edu" usage="read-write"/>

    第二种:在hibernate.cfg.xml中添加

               <class-cache class="com.lring.pojo.Edu" usage="read-write"/>

 

4、选择缓存策略(usage)

       <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:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略。

 

ehcache下载地址http://sourceforge.net/projects/ehcache/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics