Hibernate+EhCache配置二级缓存

时间:2023-03-09 03:59:37
Hibernate+EhCache配置二级缓存

步骤:

第一步:加入ehcache.jar

第二步: 在src目录下新建一个文件,名为:ehcache.xml

第三步:在hibernate配置文件的<session-factory>下配置

配置的具体信息:

ehcache.xml的具体配置:

<?xml version="1.0" encoding="UTF-8"?>
<!--
      maxEntriesLocalHeap: 在内存中缓存的element的最大数目。
      maxEntriesLocalDisk: 在磁盘上缓存的element的最大数目,默认值为0,表示不限制。
      eternal: 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,
                  如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断。
      timeToIdleSeconds="10"  缓存空闲时间   默认值0 一直存活
      timeToLiveSeconds="15"  缓存最大存活时间    默认值0 一直存活
      diskExpiryThreadIntervalSeconds:磁盘数据的有效时间
      memoryStoreEvictionPolicy="LFU"
          FIFO ,first in first out (先进先出).
        LFU , Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit
               值最小的将会被清出缓存。
        LRU ,Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,
                而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
      <persistence strategy="localTempSwap"/>  内存存满后将数据存入硬盘
 -->

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">

    <!-- <diskStore path="java.io.tmpdir"/> -->
    <diskStore path="E:\\cache4"/>
    <defaultCache
            maxEntriesLocalHeap="2"
            maxEntriesLocalDisk="10000000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskSpoolBufferSizeMB="30"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
</ehcache>

在hibernate中的配置:

<!-- 开启二级缓存 -->
 <property name="hibernate.cache.use_second_level_cache">true</property>
 <!-- 二级缓存类别:EhCache,OSCache,JbossCache -->
 <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>