代码改变世界

13、Hibernate的二级缓存

2015-10-11 20:09  怡红院丿无痕  阅读(137)  评论(0编辑  收藏  举报

1、hibernate.cfg.xml文件的配置

        <!-- 设置二级缓存为true -->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <!--设置相应的查询缓存 -->
        <property name="hibernate.cache.use_query_cache">true</property>
        <!-- 设置二级缓存所提供的类 -->
        <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>
        <!-- 在hibernate4.0之后需要设置facotory_class,这是高速缓存提供程序,
             并且在Hibernate4都封装在了 Hibernate4以后都封装到org.hibernate.cache.ehcache.EhCacheRegionFactory -->
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
        <!-- 说明ehcache的配置文件路径 -->
        <property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>

2、ehcache.xml的文件的配置

<ehcache>

    
    <diskStore path="d:/cache"/>


   
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

   
   <!-- 每一个独立的cache可以单独为不同的对象进行设置 -->
    <cache name="org.zttc.itat.model.Student"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->

    <!-- Place configuration for your caches following -->

</ehcache>

 cache参数详解: 
● name:指定区域名 
● maxElementsInMemory :缓存在内存中的最大数目 
● maxElementsOnDisk:缓存在磁盘上的最大数目 
● eternal :设置是否永远不过期 
● overflowToDisk : 硬盘溢出数目 
● timeToIdleSeconds :对象处于空闲状态的最多秒数后销毁 
● timeToLiveSeconds :对象处于缓存状态的最多秒数后销毁 
● memoryStoreEvictionPolicy:缓存算法,有LRU(默认)、LFU、LFU 

关于缓存算法,常见有三种: 
● LRU:(Least Rencently Used)新来的对象替换掉使用时间算最近很少使用的对象 
● LFU:(Least Frequently Used)替换掉按命中率高低算比较低的对象 
● LFU:(First In First Out)把最早进入二级缓存的对象替换掉