ehcache基本使用

maven

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

        <!-- ehcache2.8需要日志组件 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.2</version>
        </dependency>


ehcache配置文件

<ehcache>
    <!-- <diskStore path="java.io.tmpdir" /> -->
    
    <diskStore path="c:\\ehcache"/>
    
    <defaultCache 
        maxElementsInMemory="10000" 
        eternal="false"
        timeToIdleSeconds="120" 
        timeToLiveSeconds="120" 
        overflowToDisk="true"
        maxElementsOnDisk="10000000" 
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120" 
        memoryStoreEvictionPolicy="LRU" />


    <cache name="httpCache" 
        maxElementsInMemory="10000" 
        eternal="true"
        timeToIdleSeconds="0" 
        timeToLiveSeconds="0"  
        overflowToDisk="true"
        maxElementsOnDisk="10000000" 
        diskPersistent="true"
        diskExpiryThreadIntervalSeconds="120" 
        memoryStoreEvictionPolicy="LRU" />
</ehcache>


示例代码

package my.httpClient;

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EFCacheXml {

    public static void main(String[] args) {

        CacheManager cacheManager = CacheManager.create(); // 单例
        // CacheManager cacheManager = new CacheManager();
        // CacheManager cacheManager = new
        // CacheManager("src/main/java/ehcache.xml");
        // CacheManager cacheManager = CacheManager.getInstance();

        Cache cache = cacheManager.getCache("httpCache");

        // 加入cache
        cache.put(new Element("key1", "value3333"));

        // 取出cache
        Element element = cache.get("key1");
        Serializable value = element.getValue();
        System.out.println(value);

        cache.flush(); // 将内容写到磁盘上

        cacheManager.shutdown();

    }

}

 

你可能感兴趣的:(ehcache基本使用)