缓存技术 oscache、ehcache使用之ehcache

 

1、ehcache简介:

首先对于ehcache做个简单介绍:

         EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

下图是 Ehcache 在应用程序中的位置:

 

 

主要的特性有:

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

在线API doc:http://www.ostools.net/apidocs/apidoc?api=ehcache2.5.2

 

2、ehcache实际应用

           我们的一个接受中心项目主要接收数据、处理数据,不做前端展示 ;采用的缓存框架是ehcache。

 在启动jvm的时候,将需要缓存的数据交给ehcache管理,ehcache有两种存储方式;磁盘和内存;ehcache既可以单独使用,亦可以配合其他框架使用,如用spring实现ehcache,配合hibernate、mybatis使用;

 A、单独使用ehcache

           使用CacheManager 创建并管理Cache ,创建CacheManager有4种方式:

    a1. 使用默认配置文件创建 (默认配置文件:ehcache.xml)

java代码:
               CacheManager manager = CacheManager.create(); 

  a2;使用指定配置文件创建 

java代码:
              CacheManager manager = CacheManager.create("src/rescoure/config/ehcache.xml");  

a3:从classpath中找寻配置文件并创建 

java代码:

            URL url = getClass().getResource("/anothername.xml");   

            CacheManager manager = CacheManager.create(url);

a4:通过输入流创建

java代码:

           InputStream fis = new FileInputStream(new File("src/rescoure/config/ehcache.xml").getAbsolutePath());   

            try {   

                   manager = CacheManager.create(fis);   

            }catch(Exception e){

                 log.error(e.getMessage(),e);

            } finally {   

            fis.close();

            }

:卸载CacheManager ,关闭Cache 

java代码:

      manager.shutdown();  

 

 具体的API如下所示;       

Constructor Summary
CacheManager()
          Constructor.
CacheManager(Configuration configuration)
          An constructor for CacheManager, which takes a configuration object, rather than one created by parsing an ehcache.xml file.
CacheManager(InputStream configurationInputStream)
          An ordinary constructor for CacheManager.
CacheManager(String configurationFileName)
          An ordinary constructor for CacheManager.
CacheManager(URL configurationURL)
          An ordinary constructor for CacheManager

 

默认的配置文件: ehcache配置(ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>

<ehcache name="PersonCache">

   <defaultCache

      maxElementsInMemory="100"

      eternal="false"

      timeToIdleSeconds="1200"

      timeToLiveSeconds="1200"

      overflowToDisk="false">

    </defaultCache>

   <cache name="sampleCache1"
         maxElementsInMemory="100"
         maxElementsOnDisk="0"
         eternal="false"
         timeToIdleSeconds="120"
         timeToLiveSeconds="0">
    <terracotta/>

  </cache>
  </cache>

</ehcache>
 

cache参数详解:

            name:指定区域名 
            maxElementsInMemory :缓存在内存中的最大数目
            maxElementsOnDisk:缓存在磁盘上的最大数目
            eternal :缓存是否持久
            overflowToDisk : 硬盘溢出数目
            timeToIdleSeconds :当缓存条目闲置n秒后销毁       

            timeToLiveSeconds :当缓存条目存活n秒后销毁          

            memoryStoreEvictionPolicy:缓存算法,有LRU(默认)、LFU、FIFO


B、使用Cache

添加Cache到CacheManegr中也有多种方式;

b1、取得配置文件中预先 定义的name="sampleCache1"> 设置,通过CacheManager生成一个Cache

java代码:

             CacheManager manager = CacheManager.create();  //创建CacheManager

            Cache cache = manager.getCache("sampleCache1");  //使用创建的CacheManager创建一个cache

b2、置一个名为sampleCache2的新cache,test属性为默认 

java代码: 
            CacheManager manager = CacheManager.create();   
            manager.addCache("sampleCache2");

b3、设置一个名为sampleCache3的新cache,并定义其属性 

java代码:

            CacheManager manager = CacheManager.create();   
            Cache cache = new Cache("sampleCache3", 1, true, false, 5, 2);   
            manager.addCache(cache); 

 

相应的API如下:

net.sf.ehcache
Class CacheManager

java.lang.Object
  extended by net.sf.ehcache.CacheManag

 

 voidaddCache(Cache cache)
          Adds a Cache to the CacheManager.
 voidaddCache(Ehcache cache)
          Adds an Ehcache to the CacheManager.
 voidaddCache(String cacheName)
          Adds a Ehcache based on the defaultCache with the given name.

 

net.sf.ehcache
Class Cache

java.lang.Object
  extended by net.sf.ehcache.Cache

Cache(String name, int maxElementsInMemory, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds)
          1.0 Constructor.
Cache(String name, int maxElementsInMemory, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds)
          1.1 Constructor.
Cache(String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds,RegisteredEventListeners registeredEventListeners)
          1.2 Constructor

其他更高版本的方法。。。。

到此,我们已经往CacheManage添加Cache完成,下面就是操作Cache中的元素,主要是增删改查;

C、操作Cache中的元素

    c1、增加元素:

    java代码:

    Element element = new Element("key1", "value1");  
    cache.put(new Element(element);  //将key为key1,value为value1的元素 放进cache中

  

    c2、修改元素:

    java代码:

    Element element = new Element("key1", "value2");  
    cache.replace(element);  //如果key为key1的元素存在cache中,就 将key为key1,value为value2的这个元素放进cache中,之前的key为key1的元素被替换

   c3、查询元素:

   java代码;

   //新增一个元素

    Element element = new Element("key1", "value1");  
    cache.put(element);  //将key为key1,value为value1的元素 放进cache中

  //修改key为key1的元素

  cache.replace(new Element("key1", "value2")); 

 //查询key为key1的元素

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

c4、删除元素:

 java代码;

 boolean  isRemove =  cache.remove("key1");

所以大概步骤为: 
第一步:生成CacheManager对象 
第二步:生成Cache对象 
第三步:向Cache对象里添加由key,value组成的键值对的Element元素

 

 


 

net.sf.ehcache
Class Cache

 Elementget(Object key)
          Gets an element from the cache.
 Elementget(Serializable key)
          Gets an element from the cache.
 Map<Object,Element>getAll(Collection<?> keys)
          Gets all the elements from the cache for the keys provided.
int                getSize()
          Gets the size of the cache.
 void              put(Element element)
          Put an element in the cache.
 voidput(Element element, boolean doNotNotifyCacheReplicators)
          Put an element in the cache.
 voidputAll(Collection<Element> elements)
          Puts a collection of elements in the cache.
   booleanremove(Object key, boolean doNotNotifyCacheReplicators)
          Removes an Element from the Cache.
 booeanremove(Serializable key)
          Removes an Element from the Cache.
 booleanremove(Serializable key, boolean doNotNotifyCacheReplicators)
          Removes an Element from the Cache.
                voidremoveAll()
          Removes all cached items.
 Elementreplace(Element element)
          Replace the cached element only if an Element is currently cached for this key
       boolean      replace(Element old,Element element)
          Replace the cached element only if the current Element is equal to the supplied old Element.

 

以上是ehcache的简单应用,ehcache的优点和缺点接下来将一一讲解:

 

 

附:常用缓存技术说明:  http://sishuok.com/forum/posts/list/275.html


 Ehcache整合spring 使用页面 、对象缓存 : http://www.cnblogs.com/hoojo/archive/2012/07/12/2587556.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值