Ehcache中核心类和方法

Ehcache核心类和方法

 

EhCache里面有一个CacheManager类型,它负责管理cacheCache里面存储着Element对象,Element必须是key-value对。Cache是实际物理实现的,在内存中或者磁盘。这些组件的逻辑表示就是下面即将要讨论的类。他们的方法提供了可编程的访问方式。

 

CacheManager

负责Cache的创建、访问、移除。

 

CacheManager创建

CacheManager支持两种创建模式:单例(Singleton mode)和实例(InstanceMode)。

2.5之前的版本中,在同一个JVM中允许存在任意数量相同名字的CacheManager。每调用new CacheManager(...)一次,就会产生一个新的CacheManager实例,而不管已经存在多少个。调用CacheManager.create(...),则返回的是已经存在的那个配置对应的单例CacheManager,如果不存在,则创建一个。


2.5之后的版本,不允许在同一个JVM内存在多个具有相同名字的CacheManager。创建非单例实例的CacheManager()构造函数可能会打破这一规则,但是会抛出NPE异常。如果你的代码要在同一个JVM创建多个同名的实例,请使用静态方法CacheManager.create(),总是返回对应名的CacheManager(如果已经存在),否则创建一个。

 

事实上,我们可以直接利用Spring中的EhCacheManagerFactoryBean[spring2.5.4]来帮我们完成CacheManager的创建,看看它的具体创建方式:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. if (this.shared) {  
  2.             // Shared CacheManager singleton at the VM level.  
  3.             if (this.configLocation != null) {  
  4.                 this.cacheManager = CacheManager.create(this.configLocation.getInputStream());  
  5.             }  
  6.             else {  
  7.                 this.cacheManager = CacheManager.create();  
  8.             }  
  9.         }  
  10.         else {  
  11.             // Independent CacheManager instance (the default).  
  12.             if (this.configLocation != null) {  
  13.                 this.cacheManager = new CacheManager(this.configLocation.getInputStream());  
  14.             }  
  15.             else {  
  16.                 this.cacheManager = new CacheManager();  
  17.             }  
  18.         }  
  19.         if (this.cacheManagerName != null) {  
  20.             this.cacheManager.setName(this.cacheManagerName);  
  21.         }  



EhCache2.5.2及其以上版本的创建方法归纳如下:

  • CacheManager.newInstance(Configuration configuration) :创建一个新的CacheManager 对象或者返回已经存在的对应配置中名字的CacheManager
  • CacheManager.create():创建一个新的默认配置的单例CacheManager ,或者返回一个已经存在的单例。
  • CacheManager.create(Configuration configuration),创建一个对应传入配置文件中名字的单例CacheManager,或者返回已经存在的单例CacheManager。
  • new CacheManager(Configuration configuration),创建一个新的CacheManager,或者如果对应配置的CacheManager已经存在或配置参数为空,抛出异常。

 

Instance Mode中,如果Cache均使用MemoryStore,则没有什么特别需要注意的。但是如果使用了DIskStore,那么每个CacheManager必须具有不同的diskStore路径。当一个新的CacheManager被创建的时候,需要检查没有别的CacheManager使用同样的DiskStore路径。如果有,就会抛出异常CacheException。如果CacheManager是集群中一部分,那么其监听端口必须唯一。

 

SingletonmodeInstance Mode可以混合使用,而不会产生冲突。

 

Ehcache

所有的cache都实现了接口Ehcache。每个cache都有名字和属性,且包含Element

Ehcache中的cache相当于其他缓存系统中的一块缓存区域。

 

Element

Element是存放于cache中的原子单位。它有一个key、一个value以及关于访问的记录。Element被放进到cache或者从cache移除。他们也可能会由于过期被移除,这依赖于配置。


使用实例

下面给出了一个使用Ehcache的实际例子。

首先新建一个maven java工程,在pom.xml中添加Ehcache依赖。

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <!-- Ehcache -->  
  2. <dependency>  
  3.     <groupId>net.sf.ehcache</groupId>  
  4.     <artifactId>ehcache</artifactId>  
  5.     <version>2.8.3</version>  
  6. </dependency>  
下面是java代码。代码实现的功能非常简单,即创建CacheManager,往里面存放一个Cache,然后往cache里面存数据和取数据,目的是展示Ehcache的基本使用。

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * XXX.com Inc. 
  3.  * Copyright (c) 2004-2014 All Rights Reserved. 
  4.  */  
  5. package com.test.encache;  
  6.   
  7. import net.sf.ehcache.Cache;  
  8. import net.sf.ehcache.CacheManager;  
  9. import net.sf.ehcache.Element;  
  10.   
  11. /** 
  12.  *  
  13.  * @author XXX 
  14.  * @version $Id: EncacheTest.java, v 0.1 2014年8月8日 下午5:30:03 XXX Exp $ 
  15.  */  
  16. public class EncacheTest {  
  17.     //一些配置参数  
  18.     //private final static String configFileName      = "ehcache.xml";  
  19.     //private final static int    maxEntriesLocalHeap = 1000;  
  20.     private static CacheManager cacheManager;  
  21.     static String               cacheName = "cache1";  
  22.   
  23.     public static void main(String[] args) {  
  24.         ehcacheSetUp();  
  25.   
  26.         ehcacheUse();  
  27.     }  
  28.   
  29.     private static void ehcacheSetUp() {  
  30.   
  31.         cacheManager = CacheManager.create();  
  32.   
  33.         //CacheConfiguration configuration = new CacheConfiguration(configFileName,  
  34.         //    maxEntriesLocalHeap);  
  35.   
  36.         //Cache cache = new Cache(configuration);  
  37.         cacheManager.addCache(cacheName);  
  38.   
  39.     }  
  40.   
  41.     private static void ehcacheUse() {  
  42.         Cache cache1 = cacheManager.getCache(cacheName);  
  43.         String key = "key1";  
  44.         String value = "value1";  
  45.   
  46.         writeSomeData(cache1, key, value);  
  47.   
  48.         Element element = readSomeData(cache1, key, value);  
  49.   
  50.         System.out.println(element);  
  51.     }  
  52.   
  53.     private static void writeSomeData(Cache cache, String key, String value) {  
  54.         cache.put(new Element(key, value));  
  55.     }  
  56.   
  57.     private static Element readSomeData(Cache cache, String key, String value) {  
  58.         return cache.get(key);  
  59.     }  
  60. }  

程序输出:
[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".  
  2. SLF4J: Defaulting to no-operation (NOP) logger implementation  
  3. SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.  
  4. key = key1value=value1version=1hitCount=1CreationTime = 1411807398768LastAccessTime = 1411807398771 ]  

其中的错误信息是因为没有配置日志相关的SLF4J所致。


下面我们要配置日志。首先在pom.xml中添加依赖:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <!-- SLF4J -->  
  2. <dependency>  
  3.     <groupId>org.slf4j</groupId>  
  4.     <artifactId>slf4j-log4j12</artifactId>  
  5.     <version>1.6.1</version>  
  6. ;/dependency>  
然后建立log4j的配置文件log4j.properties:

[plain]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. # Root logger option  
  2. log4j.rootLogger=INFO, file, stdout  
  3. log4j.logger.com.test.encache.EncacheTest=INFO,file  
  4.    
  5. # Direct log messages to a log file  
  6. log4j.appender.file=org.apache.log4j.DailyRollingFileAppender  
  7. log4j.appender.file.File=C:\\logging.log  
  8. log4j.appender.file.layout=org.apache.log4j.PatternLayout  
  9. log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n  
  10.    
  11. # Direct log messages to stdout  
  12. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  13. log4j.appender.stdout.Target=System.out  
  14. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  15. log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n  


并且将这个文件放置到工程的classpath下,在这里我建立的是用Eclipse创建的maven工程,将其放置在工程主目录下的\target\classes文件夹下。
然后在代码中添加logger的初始化代码:
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. private static final Logger logger    = LoggerFactory.getLogger(EncacheTest.class);  

然后就可以使用了:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. logger.info("Setup ehcache");  

输出:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. 2014-09-27 17:22:45 INFO  EncacheTest:35 - Setup ehcache  
  2. 2014-09-27 17:22:45 WARN  ConfigurationFactory:136 - No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/D:/MavenRepo/net/sf/ehcache/ehcache/2.8.3/ehcache-2.8.3.jar!/ehcache-failsafe.xml  
  3. 2014-09-27 17:22:46 WARN  DiskStorePathManager:162 - diskStorePath 'C:\Users\xxxx\AppData\Local\Temp' is already used by an existing CacheManager either in the same VM or in a different process.  
  4. The diskStore path for this CacheManager will be set to C:\Users\xxxx\AppData\Local\Temp\ehcache_auto_created7989392067865891865diskstore.  
  5. To avoid this warning consider using the CacheManager factory methods to create a singleton CacheManager or specifying a separate ehcache configuration (ehcache.xml) for each CacheManager instance.  
  6. key = key1value=value1version=1hitCount=1CreationTime = 1411809766273LastAccessTime = 1411809766276 ]  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值