文章转载自: https://blog.csdn.net/zhouzhiwengang/article/details/59838105

1.ehcahce简介 
在开发高并发量,高性能的网站应用系统时,缓存Cache起到了非常重要的作用。 
EHCache是来自sourceforge(http://ehcache.sourceforge.net/)的开源项目,也是纯Java实现的简单、快速的Cache组件。EHCache支持内存和磁盘的缓存,支持LRU、LFU和FIFO多种淘汰算法,支持分布式的Cache,可以作为Hibernate的缓存插件,是Hibernate中默认的CacheProvider。同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度。

Ehcache缓存的特点: 
1. 快速. 
2. 简单. 
3. 多种缓存策略 
4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题 
5. 缓存数据会在虚拟机重启的过程中写入磁盘 
6. 可以通过RMI、可插入API等方式进行分布式缓存 
7. 具有缓存和缓存管理器的侦听接口 
8. 支持多缓存管理器实例,以及一个实例的多个缓存区域 
9. 提供Hibernate的缓存实现

2.Ehcache缓存- 解读Ehcache配置文件ehcache.xml 
缓存的配置有很多选项,主要集中在ehcache.xml里。比如缓存的名称,监听器等。Ehcache提供了默认的配置文件。同时可以自己指定缓存,比如

  1. <diskStore path="D:/work2/renhewww/cache"/>   
  2. <cache name=" sampleCache1"   
  3.       maxElementsInMemory="1"   
  4.            maxElementsOnDisk="10000"   
  5.            eternal="false"   
  6.            overflowToDisk="true"   
  7.            diskSpoolBufferSizeMB="20"   
  8.            diskPersistent="true"   
  9.            timeToIdleSeconds="43200"   
  10.            timeToLiveSeconds="86400"   
  11.            memoryStoreEvictionPolicy="LFU"   
  12.         />   

各配置参数的含义: 
name:Cache的唯一标识 
maxElementsInMemory:缓存中允许创建的最大对象数 
eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。 
timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是 0 就意味着元素可以停顿无穷长的时间。 
timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。 
overflowToDisk:内存不足时,是否启用磁盘缓存。 
memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。LRU和FIFO算法这里就不做介绍。LFU算法直接淘汰使用比较少的对象,在内存保留的都是一些经常访问的对象。对于大部分网站项目,该算法比较适用。 
如果应用需要配置多个不同命名并采用不同参数的Cache,可以相应修改配置文件,增加需要的Cache配置即可。

3.Ehcache缓存的使用 
3.1 安装ehcache 
Ehcache 的特点,是一个纯Java ,过程中(也可以理解成插入式)缓存实现,单独安装Ehcache ,需把ehcache-X.X.jar 和相关类库方到classpath中。如项目已安装了Hibernate ,则不需要做什么,直接可以使用Ehcache 。

如果使用maven,可以在pom.xml里配置:

  1. <dependency>  
  2.           <groupId>net.sf.ehcache</groupId>  
  3.           <artifactId>ehcache</artifactId>  
  4.           <version>2.9.0</version>  
  5. </dependency>  

3.2 生成CacheManager 
使用CacheManager 创建并管理Cache大概步骤为: 
第一步:生成CacheManager对象 
第二步:生成Cache对象 
第三步:向Cache对象里添加由key,value组成的键值对的Element元素 
第四步:关闭CacheManager。

1.创建CacheManager有4种方式: 
方式一:使用默认配置文件创建 
Ehcache有默认的配置文件ehcache.xml,里面有默认的配置和一个默认的缓存。

  1. CacheManager manager = CacheManager.create();

方式二:使用指定配置文件创建

  1. CacheManager manager =CacheManager.create("src/config/ehcache.xml");

方式三:从classpath中找寻配置文件并创建

  1. URL url = getClass().getResource("/anothername.xml");
  2. CacheManager manager = CacheManager.create(url);

方式四:通过输入流创建

  1. InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());    
  2.   
  3. try  
  4. {    
  5.     manager = CacheManager.create(fis);    
  6. }   
  7. finally  
  8. {    
  9.     if (fis != null)  
  10.     {  
  11.         fis.close();  
  12.     }  
  13. }  

// 使用manager移除指定名称的Cache对象

  1. manager.removeCache("demoCache");

可以通过调用manager.removalAll()来移除所有的Cache。

2 创建Cache 
通过CacheManager创建Cache:

  1. Cache cache = manager.getCache("sampleCache1");

3 利用cache存取数据 
存储数据

  1. Element element = new Element("key1", "value1");
  2. cache.put(new Element(element);

获取数据

  1. Element element = cache.get("key1");

//从Cache中移除一个元素

  1. cache.remove("key");

注意:可以直接使用上面的API进行数据对象的缓存,这里需要注意的是对于缓存的对象都是必须可序列化的。

4.缓存的关闭

  1. manager.shutdown();

3.3 实例

  1. import net.sf.ehcache.Cache;  
  2. import net.sf.ehcache.CacheManager;  
  3. import net.sf.ehcache.Element;  
  4.   
  5. public class Ehcache  
  6. {  
  7.     public static void main(String[] args)  
  8.     {  
  9.         CacheManager manager = CacheManager.create("src/main/resources/conf/ehcache.xml");  
  10.         Cache cache = manager.getCache("sampleCache1");  
  11.         Element element = new Element("key","value");  
  12.         cache.put(element);  
  13.           
  14.         System.out.println(cache.get("key"));  
  15.           
  16.         manager.shutdown();  
  17. } 

输出: 
[ key = key, value=value, version=1, hitCount=1, CreationTime = 1414933551601, LastAccessTime = 1414933551601 ]

更多资料:https://blog.csdn.net/vbirdbest/article/details/72763048

ehcache 简介和基本api使用的更多相关文章

  1. Ehcache(2.9.x) - API Developer Guide, Key Classes and Methods

    About the Key Classes Ehcache consists of a CacheManager, which manages logical data sets represente ...

  2. Ehcache(2.9.x) - API Developer Guide, Basic Caching

    Creating a CacheManager All usages of the Ehcache API start with the creation of a CacheManager. The ...

  3. Ehcache(2.9.x) - API Developer Guide, Searching a Cache

    About Searching The Search API allows you to execute arbitrarily complex queries against caches. The ...

  4. Ehcache(2.9.x) - API Developer Guide, Using Explicit Locking

    About Explicit Locking Ehcache contains an implementation which provides for explicit locking, using ...

  5. Ehcache(2.9.x) - API Developer Guide, Transaction Support

    About Transaction Support Transactions are supported in versions of Ehcache 2.0 and higher. The 2.3. ...

  6. Ehcache(2.9.x) - API Developer Guide, Write-Through and Write-Behind Caches

    About Write-Through and Write-Behind Caches Write-through caching is a caching pattern where writes ...

  7. Ehcache(2.9.x) - API Developer Guide, Cache Eviction Algorithms

    About Cache Eviction Algorithms A cache eviction algorithm is a way of deciding which element to evi ...

  8. web API简介(一):API,Ajax和Fetch

    概述 今天逛MDN,无意中看到了web API简介,觉得挺有意思的,就认真读了一下. 下面是我在读的时候对感兴趣的东西的总结,供自己开发时参考,相信对其他人也有用. 什么是API API (Appli ...

  9. java.net.URI 简介 文档 API

    URI 简介 文档地址:http://tool.oschina.net/apidocs/apidoc?api=jdk-zh public final class java.net.URI extend ...

随机推荐

  1. 如何在vscode中调试python scrapy爬虫

    本文环境为 Win10 64bit+VS Code+Python3.6,步骤简单罗列下,此方法可以不用单独建一个Py入口来调用命令行 安装Python,从官网下载,过程略,这里主要注意将python目 ...

  2. SIM800C 连接服务器

    AT+CIPSTART=TCP,域名,端口号 OK 只返回OK,这种情况,说明域名的服务器出错了,OK表示格式正确,但是实际上的TCP是没有连接上的. 测试库服务器出错的时候,就是这种情况 实际连上了 ...

  3. MySQL 大表优化方案(长文)

    当MySQL单表记录数过大时,增删改查性能都会急剧下降,可以参考以下步骤来优化: 单表优化 除非单表数据未来会一直不断上涨,否则不要一开始就考虑拆分,拆分会带来逻辑.部署.运维的各种复杂度,一般以整型 ...

  4. mysql脚本手动修改成oracle脚本

    今天有一个需求,立了一个新项目,新项目初步定了使用了现有的框架,但数据库要求由原来的mysql改成oracle,所以原来的基础版本的数据库脚本就需要修改成符合oracle的脚本,修改完成后,总结了一下 ...

  5. jQuery 学习笔记(5)(事件绑定与解绑、事件冒泡与事件默认行为、事件的自动触发、自定义事件、事件命名空间、事件委托、移入移出事件)

    1.事件绑定: .eventName(fn) //编码效率略高,但部分事件jQuery没有实现 .on(eventName, fn) //编码效率略低,所有事件均可以添加 注意点:可以同时添加多个相同 ...

  6. pandas apply 添加进度条

    Way:from tqdm import tqdmimport pandas as pdtqdm.pandas(desc='pandas bar')df['title_content'] = df.p ...

  7. python 中为什么不需要重载 参数*arg和**args

    函数重载主要是为了解决两个问题. (1)可变参数类型. (2) 可变参数个数. 另外,一个基本的设计原则是,仅仅当两个函数除了参数类型和参数个数不同以外,其功能是完全相同的,此时才使用函数重载,如果两 ...

  8. cocos2d-x JS 富文本

    var str1 = "兑换成功后,系统会生成“";var str2 = "红包兑换码";var str3 = "”,请复制该兑换码,并粘贴在&quo ...

  9. 实验隐藏参数"_allow_resetlogs_corruption"的使用

    实验环境:OEL 5.7 + Oracle 10.2.0.5 Tips:该参数仅在特殊恢复场景下使用,需要在专业Oracle工程师指导下进行操作. 1.隐藏参数说明 2.故障场景再现 3.非常规恢复 ...

  10. Linux C++ IDEs

    个人推荐CLion, Visual Studio, Netbeans, Eclipse CDT排名部分先后,纯属个人偏好. 还有一点需要说明的是,笔者只用这几个工具写代码,也就是用他们提供的代码提示, ...