简单的EhCache使用

1、配置文件如下:

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

<diskStore path="d:\ehcache\tmpdir" />
<!-- 
<cacheManagerEventListernerFactory class="" property="" />
 -->
<defaultCache 
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="1200000"
timeToLiveSeconds="1200000"
overflowToDisk="true" />
 
 <cache name="icache-global"
maxElementsInMemory="1"
maxElementsOnDisk="1"
eternal="true"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
overflowToDisk="true"
 />
 
 
<!-- 测试用 -->
    <cache name="SimplePageCachingFilter"
           maxElementsInMemory="10"    
           maxElementsOnDisk="10"      
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="100"
           timeToLiveSeconds="30"
           memoryStoreEvictionPolicy="LFU"
            />
<!-- FIFO先进先出  LFU最少被使用   LRU最近最少使用-->
    <cache name="SimplePageFragmentCachingFilter"
           maxElementsInMemory="1"
           maxElementsOnDisk="1"
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
            />
</ehcache>

2、具体使用规则如下:

package com.laoxu.test.day04.ehCacheDemo;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
 * java缓存ehCache使用
 */
public class EhCacheTest {
    
    
    @SuppressWarnings("deprecation")
    public void init(){
        CacheManager manager = CacheManager.create("src/main/resources/com/laoxu/test/day04/ehCacheDemo/cacheConfig.xml");
        String[] names = manager.getCacheNames();
        for (String name : names) {
            System.out.println("ehcacheNames : "+name);
        }
        Cache cache = manager.getCache(names[0]);
        cache.put(new Element("key1", "value1"));
        Element element1 = cache.get("key1");
        System.out.println("value : "+element1.getValue());
        System.out.println("objectValue : "+(String)element1.getObjectValue());
        cache.flush();
        manager.shutdown();
        
    }
    
    public static void main(String[] args) {
        EhCacheTest test = new EhCacheTest();
        test.init();
    }
    
}
原文地址:https://www.cnblogs.com/xuzhenmin/p/3383747.html