spring4.x - ehcache-2.x

ehcache2.8.1的常用标签和属性介绍,包含设置两种监听方式:

diskStore标签path属性:指定数据存储位置,可指定磁盘中的文件夹位置

cacheManagerEventListenerFactory标签:
    class属性:必须指定,表示对应的CacheManagerEventListenerFactory实现类全名。
    properties属性:可选,用来指定CacheManagerEventListenerFactory在创建CacheManagerEventListener时需要使用的属性,里面
                   是键值对的形式,多个属性之间默认用逗号隔开。如“prop1=val1,prop2=val2”。
    propertySeparator属性:可选,用来指定properties属性之间的分隔符。

cache和defaultCache(默认的管理策略)标签的某些属性:
以下属性是必须的:
    name:Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)。
    maxElementsInMemory:在内存中缓存的element的最大数目。
    maxElementsOnDisk:在磁盘上缓存的element的最大数目,默认值为0,表示不限制。
    eternal:设定缓存的elements是否永远不过期。true,则缓存的数据始终有效,false(默认)那么还要根据timeToIdleSeconds,
            timeToLiveSeconds判断。
    overflowToDisk: 如果内存中数据超过内存限制,是否要缓存到磁盘上。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实
                     现了Serializable接口才行
以下属性是可选的:
    timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,
                        如果处于空闲状态的时间超过了timeToIdleSeconds属性 值,这个对象就会过期,EHCache将把它从缓存中清
                        空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态
    timeToLiveSeconds: 设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,
                        如果处于缓存中的时间超过了timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。
                        只有当eternal属性为false,该属性才有 效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。
                        timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义。
    diskPersistent: 是否缓存虚拟机重启期数据,是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名
                     为cache名称,后缀名为index的文件,这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加
                     载到内存,要想把 cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后
                     要调用flush()方法。
    diskExpiryThreadIntervalSeconds: 磁盘失效线程运行时间间隔,默认为120秒
    diskSpoolBufferSizeMB: 磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。
    memoryStoreEvictionPolicy: 如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU(最近最少使用,默认策略)、
                                FIFO(先进先出)、LFU(最少访问次数)

cache和defaultCache(默认的管理策略)标签的子标签:
    class:必写,指定当前CacheEventListenerFactory对应的Java类全名称。
    properties:选写,指定在构建CacheEventListenerFactory时需传入的属性键值对,多个属性之间默认用逗号分开
                如:“prop1=value1,prop2=value2”。
    propertySeparator:选写,指定properties中多个属性之间的分隔符。
    listenFor:选写,表示在集群环境下可以监听到的Cache事件的范围,可选值有local、remote和all。local代表只监听本节点的Cache
               事件,remote代表只监听其他节点的Cache事件,all代表监听所有的Cache事件。默认是all。
   与CacheManagerEventListenerFactory不同的是一个Cache可以定义多个CacheEventListenerFactory。

简单例子

ehcache.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
    <diskStore path="java.io.tmpdir"/>
​
    <!-- 指定我们自定义的监听管理工厂,然后通过这个工厂指定以下缓存所在的管理器对应的监听器 -->
    <cacheManagerEventListenerFactory class="springEhCache.MyCacheManagerEventListenerFactory"/>
​
    <!-- 设定缓存的默认数据过期策略 -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="10"
            timeToLiveSeconds="20"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120">
        <cacheEventListenerFactory class="springEhCache.MyCacheEventListenerFactory"/>
    </defaultCache>
​
    <cache name="ehCacheTest"
           maxElementsInMemory="10000"
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="10"
           timeToLiveSeconds="20">
        <cacheEventListenerFactory class="springEhCache.MyCacheEventListenerFactory"/>
    </cache>
​
</ehcache>

spring-ehcache.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/cache
           http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
​
    <!-- 自动扫描注解的bean,指定扫描路径 -->
    <context:component-scan base-package="springEhCache" />
​
    <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效 -->
    <cache:annotation-driven cache-manager="springEhCacheCacheManager"/>
​
    <!-- 实例化一个缓存管理器,指定唯一对应的缓存配置文件 -->
    <bean id="cacheManage" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:springEhCache/ehcache.xml"></property>
    </bean>
​
    <!-- 把cacheManage注入到Spring来管理,在后续的操作中获取这个对象,然后获取cacheManage来增删...缓存 -->
    <bean id="springEhCacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="cacheManage"></property>
    </bean>
​
</beans>

业务操作类:

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
​
/**
 * Created by Blossom on 2018/9/25.
 */
@Service
public class EhCacheService {
​
    @Cacheable(value="ehCacheTest",key="#param")
    public String getTime(String param){
        System.out.println("从数据库查询:");
        return "时间" + param;
    }
}

cacheManagerEventListenerFactory:

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.event.CacheManagerEventListener;
import net.sf.ehcache.event.CacheManagerEventListenerFactory;
import java.util.Properties;
​
/**
 * 在生成对应的CacheManagerEventListener进行返回时,我们可以使用当前的CacheManager以及在ehcache.xml文件中
 * 定义CacheManagerEventListenerFactory时指定的属性Properties。通过CacheManagerEventListenerFactory我们可以实现为不同的CacheManager使用
 * 不同的CacheManagerEventListener。
 *
 * Created by Blossom on 2018/9/25.
 */
public class MyCacheManagerEventListenerFactory extends
        CacheManagerEventListenerFactory {
​
    @Override
    public CacheManagerEventListener createCacheManagerEventListener(
            CacheManager cacheManager, Properties properties) {
        System.out.println("进入MyCacheManagerEventListenerFactory");
        return new MyCacheManagerEventListener(cacheManager);
    }
​
}

CacheManagerEventListener:

import net.sf.ehcache.CacheException;
import net.sf.ehcache.Status;
import net.sf.ehcache.event.CacheManagerEventListener;
import net.sf.ehcache.CacheManager;
​
/**
 * Ehcache中定义了一个CacheManagerEventListener接口来监听CacheManager的事件
 *
 * Created by Blossom on 2018/9/25.
 */
public class MyCacheManagerEventListener implements CacheManagerEventListener {
​
    private final CacheManager cacheManager;
​
    public MyCacheManagerEventListener(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }
​
    /**
     * 在CacheManagerEventListener实现类实例化后被调用,用于初始化CacheManagerEventListener
     */
    @Override
    public void init() throws CacheException {
        System.out.println("init.....");
    }
​
    /**
     * 返回当前CacheManagerEventListener所处的状态,可选值有STATUS_UNINITIALISED、 STATUS_ALIVE和STATUS_SHUTDOWN
     */
    @Override
    public Status getStatus() {
        System.out.println("getStatus.....");
        return null;
    }
​
    /**
     * 用于释放资源
     */
    @Override
    public void dispose() throws CacheException {
        System.out.println("dispose......");
    }
​
    /**
     * 在往CacheManager中添加Cache时被调用
     */
    @Override
    public void notifyCacheAdded(String cacheName) {
        System.out.println("cacheAdded......." + cacheName);
        System.out.println(cacheManager.getCache(cacheName));
    }
​
    /**
     * 在从CacheManager中移除Cache时被调用
     */
    @Override
    public void notifyCacheRemoved(String cacheName) {
        System.out.println("cacheRemoved......" + cacheName);
    }
​
}

cacheEventListenerFactory:

import net.sf.ehcache.event.CacheEventListener;
import net.sf.ehcache.event.CacheEventListenerFactory;
import java.util.Properties;
​
/**
 * Created by Blossom on 2018/9/25.
 */
public class MyCacheEventListenerFactory extends CacheEventListenerFactory {
​
    @Override
    public CacheEventListener createCacheEventListener(Properties properties) {
        return new MyCacheEventListener();
    }
​
}

CacheEventListener:

import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.event.CacheEventListener;

/**
 * Created by Blossom on 2018/9/25.
 */
public class MyCacheEventListener implements CacheEventListener {
​
    @Override
    public void notifyElementRemoved(Ehcache cache, Element element)
            throws CacheException {
        System.out.println("removed");
    }
​
    @Override
    public void notifyElementPut(Ehcache cache, Element element)
            throws CacheException {
        System.out.println("put");
    }
​
    @Override
    public void notifyElementUpdated(Ehcache cache, Element element)
            throws CacheException {
        System.out.println("updated");
    }
​
    @Override
    public void notifyElementExpired(Ehcache cache, Element element) {
        System.out.println("expired");
    }
​
    @Override
    public void notifyElementEvicted(Ehcache cache, Element element) {
        System.out.println("evicted");
    }
​
    @Override
    public void notifyRemoveAll(Ehcache cache) {
        System.out.println("removeAll");
    }
​
    @Override
    public void dispose() {
​
    }
​
    public Object clone() throws CloneNotSupportedException {
        System.out.println("clone");
        return null;
    }
​
}

测试:

import net.sf.ehcache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
/**
 * Created by Blossom on 2018/9/25.
 */
public class ehcacheTest {
​
    public static void main(String [] args) throws Exception{
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "springEhCache/spring-ehcache.xml");// 加载 spring 配置文件
        EhCacheService ehCacheService = (EhCacheService)context.getBean("ehCacheService");
        System.out.println(ehCacheService.getTime("1"));
        Thread.sleep(2000);
        System.out.println(ehCacheService.getTime("1"));
        //测试timeToIdleSeconds属性
        Thread.sleep(11000);
        System.out.println(ehCacheService.getTime("1"));
        System.out.println(ehCacheService.getTime("2"));
        System.out.println(ehCacheService.getTime("2"));
        System.out.println(ehCacheService.getTime("1"));
​
        EhCacheCacheManager springEhCacheCacheManager = (EhCacheCacheManager)context.getBean("springEhCacheCacheManager");
        CacheManager cacheManager = springEhCacheCacheManager.getCacheManager();
        cacheManager.addCache("blossom");
        cacheManager.removeCache("blossom");
    }
​
}

测试结果:

进入MyCacheManagerEventListenerFactory
init.....
cacheAdded.......ehCacheTest
[ name = ehCacheTest status = STATUS_ALIVE eternal = false overflowToDisk = true maxEntriesLocalHeap = 10000 maxEntriesLocalDisk = 0 memoryStoreEvictionPolicy = LRU timeToLiveSeconds = 20 timeToIdleSeconds = 10 persistence = none diskExpiryThreadIntervalSeconds = 120 cacheEventListeners: springEhCache.MyCacheEventListener ; orderedCacheEventListeners:  maxBytesLocalHeap = 0 overflowToOffHeap = false maxBytesLocalOffHeap = 0 maxBytesLocalDisk = 0 pinned = false ]
从数据库查询:
put
时间1
时间1
expired
从数据库查询:
put
时间1
从数据库查询:
put
时间2
时间2
时间1
clone
cacheAdded.......blossom
[ name = blossom status = STATUS_ALIVE eternal = false overflowToDisk = true maxEntriesLocalHeap = 10000 maxEntriesLocalDisk = 0 memoryStoreEvictionPolicy = LRU timeToLiveSeconds = 20 timeToIdleSeconds = 10 persistence = none diskExpiryThreadIntervalSeconds = 120 cacheEventListeners: ; orderedCacheEventListeners:  maxBytesLocalHeap = 0 overflowToOffHeap = false maxBytesLocalOffHeap = 0 maxBytesLocalDisk = 0 pinned = false ]
cacheRemoved......blossom

猜你喜欢

转载自blog.csdn.net/blossomfzq/article/details/82868487