ehcache缓存配置

一、如何使用Ehcache

# 在pom.xml中引入依赖

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.6</version>
</dependency>

# 在src/main/resources/创建一个配置文件 ehcache.xml

默认情况下Ehcache会自动加载classpath根目录下名为ehcache.xml文件,也可以将该文件放到其他地方在使用时指定文件的位置。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

  <!-- 磁盘缓存位置 -->
  <diskStore path="java.io.tmpdir/ehcache"/>

  <!-- 默认缓存 -->
  <defaultCache
          maxEntriesLocalHeap="10000"
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          maxEntriesLocalDisk="10000000"
          diskExpiryThreadIntervalSeconds="120"
          memoryStoreEvictionPolicy="LRU">
    <persistence strategy="localTempSwap"/>
  </defaultCache>

  <!-- helloworld缓存 -->
  <cache name="HelloWorldCache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="5"
         timeToLiveSeconds="5"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>
</ehcache>

# 测试类

public class CacheTest {
    public static void main(String[] args) throws IOException {
        // 1. 创建缓存管理器。 ClassPathResource是org.springframework.core.io.ClassPathResource
        CacheManager cacheManager = CacheManager.create(new ClassPathResource("ehcache.xml").getInputStream());
        //CacheManager cacheManager = CacheManager.create();
         
        // 2. 获取缓存对象
        Cache cache = cacheManager.getCache("HelloWorldCache");
         
        // 3. 创建元素
        Element element = new Element("key1", "value1");
         
        // 4. 将元素添加到缓存
        cache.put(element);
         
        // 5. 获取缓存
        Element value = cache.get("key1");
        System.out.println("value: " + value);
        System.out.println(value.getObjectValue());
         
        // 6. 删除元素
        cache.remove("key1");
         
        Dog dog = new Dog("xiaohei", "black", 2);
        Element element2 = new Element("dog", dog);
        cache.put(element2);
        Element value2 = cache.get("dog");
        System.out.println("value2: "  + value2);
        Dog dog2 = (Dog) value2.getObjectValue();
        System.out.println(dog2);
         
        System.out.println(cache.getSize());
         
        // 7. 刷新缓存
        cache.flush();
         
        // 8. 关闭缓存管理器
        cacheManager.shutdown();
 
    }
}


public class Dog {
    private String name;
    private String color;
    private int age;
     
    public Dog() {
    }
     
    public Dog(String name, String color, int age) {
        super();
        this.name = name;
        this.color = color;
        this.age = age;
    }
     
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
     
    @Override
    public String toString() {
        return "Dog [name=" + name + ", color=" + color + ", age=" + age + "]";
    }
}

注意:类必须实现序列化接口,不需要的属性用transient修饰

二、缓存配置

xml配置方式
diskStore

path :指定磁盘存储的位置

defaultCache

默认缓存

cache

自定的缓存,当自定的配置不满足实际情况时可以通过自定义(可以包含多个cache节点)。

  • name : 缓存的名称,可以通过指定名称获取指定的某个Cache对象
  • maxElementsInMemory :内存中允许存储的最大的元素个数,0代表无限个
  • clearOnFlush:内存数量最大时是否清除。
  • eternal :设置缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。根据存储数据的不同,例如一些静态不变的数据如省市区等可以设置为永不过时
  • timeToIdleSeconds : 设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
  • timeToLiveSeconds :缓存数据的 生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。(和上面的两者取最小值)
  • overflowToDisk:内存不足时,是否启用磁盘缓存。
  • maxEntriesLocalDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
  • maxElementsOnDisk:硬盘最大缓存个数。
  • diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
  • diskPersistent:是否在VM重启时存储硬盘的缓存数据。默认值是false。
  • diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
  • memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。这里比较遗憾,Ehcache并没有提供一个用户定制策略的接口,仅仅支持三种指定策略,感觉做的不够理想。
编程方式
Cache cache = manager.getCache("mycache");
CacheConfiguration config = cache.getCacheConfiguration();
config.setTimeToIdleSeconds(60);
config.setTimeToLiveSeconds(120);
config.setmaxEntriesLocalHeap(10000);
config.setmaxEntriesLocalDisk(1000000);

三、Ehcache API

CacheManager:Cache的容器对象,并管理着(添加或删除)Cache的生命周期。

// 可以自己创建一个Cache对象添加到CacheManager中
public void addCache(Cache cache);
public synchronized void removeCache(String cacheName);

Cache:一个Cache可以包含多个Element,并被CacheManager管理。它实现了对缓存的逻辑行为。

Element:需要缓存的元素,它维护着一个键值对, 元素也可以设置有效期,0代表无限制。

获取CacheManager的方式:可以通过create()或者newInstance()方法或重载方法来创建获取CacheManager的方式

public static CacheManager create();
public static CacheManager create(String configurationFileName);
public static CacheManager create(InputStream inputStream);
public static CacheManager create(URL configurationFileURL);
 
public static CacheManager newInstance();

Ehcache的CacheManager构造函数或工厂方法被调用时,会默认加载classpath下名为ehcache.xml的配置文件。
如果加载失败,会加载Ehcache jar包中的ehcache-failsafe.xml文件,这个文件中含有简单的默认配置。

// CacheManager.create() == CacheManager.create("./src/main/resources/ehcache.xml")
// 使用Ehcache默认配置新建一个CacheManager实例
CacheManager cacheManager = CacheManager.create();
cacheManager = CacheManager.newInstance();
 
cacheManager = CacheManager.newInstance("./src/main/resources/ehcache.xml");
 
InputStream inputStream = new FileInputStream(new File("./src/main/resources/ehcache.xml"));
cacheManager = CacheManager.newInstance(inputStream);
 
String[] cacheNames = cacheManager.getCacheNames();  // [HelloWorldCache]

 

posted @ 2020-09-21 21:21  codedot  阅读(571)  评论(0编辑  收藏  举报