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

ehcache缓存使用及与spring集成

2016-04-26 00:00 169 查看
摘要: 1.ehcache简介
2.相关配置分析
3.spring集成
4.总结

1.ehcache简介

ehcache是一个Java进程内缓存框架,有如下特点:

快速简单,容易集成

支持多种缓存策略

缓存数据有两级:内存和磁盘, 无需担心容量问题

缓存数据会在虚拟机重启的过程写入磁盘

2.相关配置分析

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="txswx-ehcache">
<diskStore path="java.io.tmpdir"/>
<!-- DefaultCache setting. -->
<defaultCache maxEntriesLocalHeap="10000" eternal="true" timeToIdleSeconds="300" timeToLiveSeconds="600"
overflowToDisk="true" maxEntriesLocalDisk="100000"/>

<cache name="levelOneCache" maxElementsInMemory="1000" eternal="false"
timeToIdleSeconds="300" timeToLiveSeconds="1000" overflowToDisk="false" />
</ehcache>


name:缓存名称shiroCache
eternal:对象是否永久有效,一旦设置true,timeout将不起作用
timeToIdleSeconds:设置对象在失效前的允许闲置时间
timeToLiveSeconds:设置对象在失效前的允许存活时间
overflowToDisk: 当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中
diskPersistent:是否缓存虚拟机重启期数据
diskExpiryThreadIntervalSeconds: 磁盘失效线程运行时间间隔,默认是120秒


3.与spring集成

1. ehcache.xml

<ehcache updateCheck="false" name="shiroCache">

<!--
name:缓存名称shiroCache eternal:对象是否永久有效,一旦设置true,timeout将不起作用 timeToIdleSeconds:设置对象在失效前的允许闲置时间 timeToLiveSeconds:设置对象在失效前的允许存活时间 overflowToDisk: 当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中 diskPersistent:是否缓存虚拟机重启期数据 diskExpiryThreadIntervalSeconds: 磁盘失效线程运行时间间隔,默认是120秒
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>


2. mvc-dispatcher-servlet.xml配置

<!-- Cache配置 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache.xml"/>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehCacheManagerFactory"/>


3.测试类

public class EhcacheTest {

private static final Logger LOG = LoggerFactory.getLogger(EhcacheTest.class);

public static void main(String[] args) {
Resource res = new ClassPathResource("mvc-dispatcher-servlet.xml");
BeanFactory factory = new XmlBeanFactory(res);

CacheManager cacheManager = (CacheManager) factory.getBean("cacheManager");
Cache cache = cacheManager.getCache("levelOneCache");

User user = null;
for (int i = 0; i < 10; i++) {
Element element = cache.get("key");
if (element == null) {
user = new User("test");
element = new Element("key", user);
cache.put(element);
LOG.info("cache object " + "  can not retrieved from cache");
}else {
user = (User)element.getValue();
LOG.info("cache object " + " can retrieve from cache");
}
}
}
}


4.总结

Ehcache在很多项目中都会被使用过, 用法比较简单,一般加些配置就可以了, Ehcache可以对页面 对象 数据进行缓存,Ehcache支持内存和磁盘的缓存, 支持分布式的cache
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ehcache spring