zoukankan      html  css  js  c++  java
  • Java缓存学习之四:EhCache

    EhCache

    关键词:纯Java的进程内缓存框架、Java分布式缓存、缓存数据有两级:内存和磁盘、缓存数据会在虚拟机重启的过程中写入磁盘、是hibernate默认的缓存provider;

    Ehcache的核心包括CacheManager、Cache和Element:
    CacheManager来管理对cache的创建,访问和移除操作;Cache是一个线程安全的数据集合的逻辑表示,是它就是缓存;Element可以理解为缓存中的key-value形式的元素。在程序中通常将需要缓存的对象放在Element中。

    默认配置文件名称:ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache updateCheck="false">
        <!-- 指定一个文件目录,当EHCache把数据写到硬盘上时,将把数据写到这个文件目录下 
        java.io.tmpdir操作系统不同 这个系统属性所表示的目录也不同
        On Windows: java.io.tmpdir:[C:DOCUME~1joshuaLOCALS~1Temp]
        On Solaris: java.io.tmpdir:[/var/tmp/]
        On Linux: java.io.tmpdir: [/tmp]
        On Mac OS X: java.io.tmpdir: [/tmp]-->
        <diskStore path="java.io.tmpdir" />
        
        <!-- 设定缓存的默认数据过期策略 -->
        <defaultCache 
            maxElementsInMemory="10000" 
            overflowToDisk="true"
            eternal="false" 
            memoryStoreEvictionPolicy="LRU" 
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="600" 
            timeToIdleSeconds="3600"
            timeToLiveSeconds="100000" 
            diskPersistent="false" />
            
         <!-- 普通缓存
         设定具体的命名缓存的数据过期策略  
            cache元素的属性:  
                name:缓存名称  
                maxElementsInMemory:内存中最大缓存对象数  
                maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大  
                eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false  
                overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。  
                diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。  
                diskPersistent:是否缓存虚拟机重启期数据  
                diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒  
                timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态  
                timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义  
                memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。  
        -->  
        <!-- 普通缓存 -->
        <cache name="CACHE1"  
               maxElementsInMemory="1000"  
               eternal="true"  
               overflowToDisk="true"/>
        
        
        <!-- 分布式缓存:RMI集群模式 -->
        <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
            properties="hostName=localhost, port=40001,socketTimeoutMillis=2000" />
        <!-- 分布式缓存:手工发现 -->
        <cacheManagerPeerProviderFactory   
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"   
        properties="peerDiscovery=manual,rmiUrls=//192.168.0.12:4567/oschina_cache|//192.168.0.13:4567/oschina_cache" /> 
        <!-- 分布式缓存:自动发现 -->
        <cacheManagerPeerProviderFactory  
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"  
        properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,  
        multicastGroupPort=4446, timeToLive=32"/>  
        
        <!-- 分布式缓存 : 需要在每个cache属性中加入<cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>-->    
        <cache 
            name="dictCache" 
            maxElementsInMemory="500" 
            overflowToDisk="true"
            eternal="true">
            <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="replicatePuts=false,replicateUpdatesViaCopy=false" />
        </cache>
    
        <cache 
            name="eternalCache" 
            maxElementsInMemory="500"
            overflowToDisk="true" 
            eternal="false" 
            timeToIdleSeconds="1200"
            timeToLiveSeconds="1200">
            <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="replicatePuts=false,replicateUpdatesViaCopy=false" />
        </cache>
        
        <!-- 页面缓存 注意:cache的name属性必需为SimplePageCachingFilter -->
        <cache name="SimplePageCachingFilter"   
               maxElementsInMemory="10"   
               overflowToDisk="true"   
               eternal="false"   
               timeToIdleSeconds="100"   
               timeToLiveSeconds="100"  
               memoryStoreEvictionPolicy="LFU" /> 
    </ehcache>

    1、普通缓存:

    cache元素的属性:
    name:缓存名称
    maxElementsInMemory:内存中最大缓存对象数
    maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大
    eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false
    overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。
    diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。
    diskPersistent:是否缓存虚拟机重启期数据
    diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒
    timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态
    timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义
    memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。

    2、分布式缓存(RMI集群)

    手工发现: 需要指定节点发现模式peerDiscovery值为manual,rmiUrls设置为另一台服务器的IP、端口和缓存名等信息。

    <cacheManagerPeerProviderFactory   
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"   
        properties="peerDiscovery=manual,rmiUrls=//192.168.0.12:4567/oschina_cache|//192.168.0.13:4567/oschina_cache" />

    自动发现: 需要指定节点发现模式peerDiscovery值为automatic自动,同时组播地址可以指定D类IP地址空间,范围从 224.0.1.0 到 238.255.255.255 中的任何一个地址。

    <cacheManagerPeerProviderFactory  
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"  
        properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,  
        multicastGroupPort=4446, timeToLive=32"/>

    注意:需要在每个cache属性中加入<cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>

    <cache 
            name="dictCache" 
            maxElementsInMemory="500" 
            overflowToDisk="true"
            eternal="true">
            <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="replicatePuts=false,replicateUpdatesViaCopy=false" />
        </cache>

    3、页面缓存:

    第一步:在web.xml文件中配置过滤器。此处对test_tag.jsp页面进行缓存。

    <filter>   
        <filter-name>testPageCachingFilter</filter-name>   
        <filter-class>net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter</filter-class>   
    </filter>  
    <filter-mapping>   
        <filter-name>testPageCachingFilter</filter-name>   
        <url-pattern>/test_tag.jsp</url-pattern>  
    </filter-mapping>

    第二步:在ehcache.xml文件中配置Cache节点。注意:cache的name属性必需为SimplePageCachingFilter。

    <cache name="SimplePageCachingFilter"   
       maxElementsInMemory="10"   
       overflowToDisk="true"   
       eternal="false"   
       timeToIdleSeconds="100"   
       timeToLiveSeconds="100"  
       memoryStoreEvictionPolicy="LFU" /> 

    4、Java中使用

    package com.buss.test;
    
    import net.sf.ehcache.Cache;
    import net.sf.ehcache.CacheManager;
    import net.sf.ehcache.Element;
    
    public class Test
    {
        public static void main(String[] args) 
        {
            //第一步 从classes目录查找ehcache.xml配置文件
            CacheManager cm = CacheManager.getInstance();
            //从classes目录查找指定名称的配置文件
            //CacheManager cm = CacheManager.create(getClass().getResource("/ehcache.xml"));
            
            //第二步 根据配置文件获得Cache实例
            Cache cache1 = cm.getCache("CACHE1");
            
            //2.1清空Cache中的所有元素 
            cache1.removeAll();
            
            //2.2往Cache中添加元素  
            cache1.put(new Element("s1",new Object()));
            cache1.put(new Element("s2","222222"));
            cache1.put(new Element("s3","333333"));
            
            //2.3从Cache中取得元素
            Element e = cache1.get("s2");
            System.out.println(e.getValue());
            //第三步 卸载缓存管理器
            cm.shutdown();
        }
    
    }

     

    参考:

    http://chenjumin.iteye.com/blog/684926     普通缓存和分布式缓存配置与使用

    http://elim.iteye.com/blog/2123030    spting cache以及与ehcache的整合

    http://raychase.iteye.com/blog/1545906   ehcache详解

  • 相关阅读:
    FreeMarker缓存处理
    freemarker入门实例与源码研究准备工作
    Freemarker常用技巧(二)
    Freemarker常用技巧(一)
    Hessian与Spring整合
    Hessian学习
    数组常见的面试题
    关于排序的实现
    Redis与Memcache的区别
    JDBC编程步骤
  • 原文地址:https://www.cnblogs.com/cac2020/p/6021167.html
Copyright © 2011-2022 走看看