您的位置:首页 > 编程语言 > Java开发

Spring整合Ehcache管理缓存

2016-10-19 11:00 495 查看

安装

Ehcache

如果你的项目使用maven管理,添加以下依赖到你的pom.xml中。

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


如果你的项目不使用maven管理,请下载


Spring

如果你的项目使用maven管理,添加以下依赖到你的pom.xml中。
spring-context-support
这个jar包中含有Spring对于缓存功能的抽象封装接口。

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>


回到顶部

Ehcache的使用

HelloWorld范例 下载

接触一种技术最快最直接的途径总是一个Hello World例子,毕竟动手实践印象更深刻,不是吗?

(1) 在classpath下添加ehcache.xml

添加一个名为helloworld的缓存。

<?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"/>

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


(2) EhcacheDemo.java

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

EhcacheDemo的工作步骤如下:

在EhcacheDemo中,我们引用ehcache.xml声明的名为helloworld的缓存来创建
Cache
对象;

然后我们用一个键值对来实例化
Element
对象;

Element
对象添加到
Cache


然后用
Cache
的get方法获取
Element
对象。

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("helloworld");

// 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());
}
}


输出

Hello, World!

Ehcache基本操作

下载

Element
Cache
CacheManager
是Ehcache最重要的API。

Element:缓存的元素,它维护着一个键值对。
Cache:它是Ehcache的核心类,它有多个
Element
,并被
CacheManager
管理。它实现了对缓存的逻辑行为。

CacheManager:
Cache
的容器对象,并管理着
Cache
的生命周期。


创建CacheManager

下面的代码列举了创建
CacheManager
的五种方式。

使用静态方法
create()
会以默认配置来创建单例的
CacheManager
实例。
newInstance()
方法是一个工厂方法,以默认配置创建一个新的
CacheManager
实例。

此外,
newInstance()
还有几个重载函数,分别可以通过传入
String
URL
InputStream
参数来加载配置文件,然后创建
CacheManager
实例。

下载

// 使用Ehcache默认配置获取单例的CacheManager实例
CacheManager.create();
String[] cacheNames = CacheManager.getInstance().getCacheNames();

// 使用Ehcache默认配置新建一个CacheManager实例
CacheManager.newInstance();
String[] cacheNames = manager.getCacheNames();

// 使用不同的配置文件分别创建一个CacheManager实例
CacheManager manager1 = CacheManager.newInstance("src/config/ehcache1.xml");
CacheManager manager2 = CacheManager.newInstance("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();

// 基于classpath下的配置文件创建CacheManager实例
URL url = getClass().getResource("/anotherconfigurationname.xml");
CacheManager manager = CacheManager.newInstance(url);

// 基于文件流得到配置文件,并创建CacheManager实例
InputStream fis = new FileInputStream(new File
("src/config/ehcache.xml").getAbsolutePath());
try {
CacheManager manager = CacheManager.newInstance(fis);
} finally {
fis.close();
}


添加缓存

需要强调一点,
Cache
对象在用
addCache
方法添加到
CacheManager
之前,是无效的。


使用CacheManager的addCache方法可以根据缓存名将ehcache.xml中声明的cache添加到容器中;它也可以直接将Cache对象添加到缓存容器中。
Cache
有多个构造函数,提供了不同方式去加载缓存的配置参数。

有时候,你可能需要使用API来动态的添加缓存,下面的例子就提供了这样的范例。

下载

// 除了可以使用xml文件中配置的缓存,你也可以使用API动态增删缓存
// 添加缓存
manager.addCache(cacheName);

// 使用默认配置添加缓存
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");

// 使用自定义配置添加缓存,注意缓存未添加进CacheManager之前并不可用
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache test = singletonManager.getCache("testCache");

// 使用特定的配置添加缓存
CacheManager manager = CacheManager.create();
Cache testCache = new Cache(
new CacheConfiguration("testCache", maxEntriesLocalHeap)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
.eternal(false)
.timeToLiveSeconds(60)
.timeToIdleSeconds(30)
.diskExpiryThreadIntervalSeconds(0)
.persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP)));
manager.addCache(testCache);


删除缓存

删除缓存比较简单,你只需要将指定的缓存名传入
removeCache
方法即可。

CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("sampleCache1");


实现基本缓存操作

Cache最重要的两个方法就是put和get,分别用来添加Element和获取Element。

/**
* 测试:使用默认配置或使用指定配置来创建CacheManager
*
* @author victor zhang
*/
public class CacheOperationTest {
private final Logger log = LoggerFactory.getLogger(CacheOperationTest.class);

/**
* 使用Ehcache默认配置(classpath下的ehcache.xml)获取单例的CacheManager实例
*/
@Test
public void operation() {
CacheManager manager = CacheManager.newInstance("src/test/resources/ehcache/ehcache.xml");

// 获得Cache的引用
Cache cache = manager.getCache("userCache");

// 将一个Element添加到Cache
cache.put(new Element("key1", "value1"));

// 获取Element,Element类支持序列化,所以下面两种方法都可以用
Element element1 = cache.get("key1");
// 获取非序列化的值
log.debug("key:{}, value:{}", element1.getObjectKey(), element1.getObjectValue());
// 获取序列化的值
log.debug("key:{}, value:{}", element1.getKey(), element1.getValue());

// 更新Cache中的Element
cache.put(new Element("key1", "value2"));
Element element2 = cache.get("key1");
log.debug("key:{}, value:{}", element2.getObjectKey(), element2.getObjectValue());

// 获取Cache的元素数
log.debug("cache size:{}", cache.getSize());

// 获取MemoryStore的元素数
log.debug("MemoryStoreSize:{}", cache.getMemoryStoreSize());

// 获取DiskStore的元素数
log.debug("DiskStoreSize:{}", cache.getDiskStoreSize());

// 移除Element
cache.remove("key1");
log.debug("cache size:{}", cache.getSize());

// 关闭当前CacheManager对象
manager.shutdown();

// 关闭CacheManager单例实例
CacheManager.getInstance().shutdown();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息