缓存技术 oscache、ehcache使用之ehcache

 

一、ehcache简介:

首先对于ehcache作个简单介绍:html

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

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

 

 

主要的特性有:算法

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

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

 

二、ehcache实际应用

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

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

 A、单独使用ehcache

           使用CacheManager 建立并管理Cache ,建立CacheManager有4种方式:框架

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

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中也有多种方式;

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

java代码:

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

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

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

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

b三、设置一个名为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
  net.sf.ehcache.CacheManag

 

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

 

net.sf.ehcache
Class Cache

java.lang.Object
  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中的元素

    c一、增长元素:

    java代码:

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

  

    c二、修改元素:

    java代码:

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

   c三、查询元素:

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

c四、删除元素:

 java代码;

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

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

 

 


 

net.sf.ehcache
Class Cache

 Element get(Object key)
          Gets an element from the cache.
 Element get(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.
 void put(Element element, boolean doNotNotifyCacheReplicators)
          Put an element in the cache.
 void putAll(Collection<Element> elements)
          Puts a collection of elements in the cache.
   boolean remove(Object key, boolean doNotNotifyCacheReplicators)
          Removes an Element from the Cache.
 booean remove(Serializable key)
          Removes an Element from the Cache.
 boolean remove(Serializable key, boolean doNotNotifyCacheReplicators)
          Removes an Element from the Cache.
                void removeAll()
          Removes all cached items.
 Element replace(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

相关文章
相关标签/搜索