Ehcache

概述

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点。它是Hibernate中的默认缓存框架。Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。缺点是没法dibug。

Maven坐标:

<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
  <version>2.10.2</version>
  <type>pom</type>
</dependency>

ehcache.xml:放在classpath下

<?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"/>
  <!-- mycache缓存 -->
  <cache name="mycache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="5"
         timeToLiveSeconds="5"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>
</ehcache>

代码如下:Ehcache会自动加载classpath根目录下名为ehcache.xml文件。

public class EhcacheDemo {
    public static void main(String[] args) throws Exception {
        // Create a cache manager
        final CacheManager cacheManager = new CacheManager();
        // create the cache called "helloworld"
        final Cache cache = cacheManager.getCache("mycache");
        // create a key to map the data to
        final String key = "greeting";
        // Create a data element
        final Element putGreeting = new Element(key, "Hello, World!");
        // Put the element into the data store
        cache.put(putGreeting);
        // Retrieve the data element
        final Element getGreeting = cache.get(key);
        // Print the value
        System.out.println(getGreeting.getObjectValue());
    }
}
原文地址:https://www.cnblogs.com/jvStarBlog/p/11032679.html