1. 程式人生 > >EhCache緩存框架的使用

EhCache緩存框架的使用

內存 int 都去 nts tor ges pro odin flush

EhCache 是一個純Java的進程內緩存框架,具有快速、精幹等特點,是Hibernate中默認的CacheProvider。

我們使用EhCache緩存框架主要是為了判斷重復Url,每次爬取一個網頁,都把Url存儲到緩存中,並且每次爬某個網頁之前,都去緩存中搜索下,假如存在的話,我們就不要爬取這個網頁了,不存在的話,我們就爬下網頁,爬取成功後,把這個Url存儲到緩存中;之所以用緩存框架,主要是速度快,相對於傳統數據庫;

主要的特性有:

1. 快速

2. 簡單

3. 多種緩存策略

4. 緩存數據有兩級:內存和磁盤,因此無需擔心容量問題

5. 緩存數據會在虛擬機重啟的過程中寫入磁盤

6. 可以通過RMI、可插入API等方式進行分布式緩存

7. 具有緩存和緩存管理器的偵聽接口

8. 支持多緩存管理器實例,以及一個實例的多個緩存區域

9. 提供Hibernate的緩存實現

項目文件結構

下載jar包->貼jar包->引入jar包

技術分享

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
 
<ehcache>
   <!-- 
         磁盤存儲:將緩存中暫時不使用的對象,轉移到硬盤,類似於Windows系統的虛擬內存
          path:指定在硬盤上存儲對象的路徑
   -->
   <diskStore path="d:\ehcache" />
    
   <!-- 
        defaultCache:默認的緩存配置信息,如果不加特殊說明,則所有對象按照此配置項處理
        maxElementsInMemory:設置了緩存的上限,最多存儲多少個記錄對象
        eternal:代表對象是否永不過期
        overflowToDisk:當內存中Element數量達到maxElementsInMemory時,Ehcache將會Element寫到磁盤中
   -->
   <defaultCache
      maxElementsInMemory="100"
      eternal="true"
      overflowToDisk="true"/>
 
     
    <cache 
      name="a"
      maxElementsInMemory="100"
      eternal="true"
      overflowToDisk="true"/>
 
</ehcache>

  

代碼如下:

package com.zhi.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class Demo {

	public static void main(String[] args) {
		// 根據ehcache.xml配置文件創建Cache管理器
        CacheManager manager=CacheManager.create("ehcache.xml");
        Cache c=manager.getCache("a"); // 獲取指定Cache
        Element e=new Element("oracle","zhi"); // 實例化一個元素
        c.put(e); // 把一個元素添加到Cache中
         
        Element e2=c.get("oracle"); // 根據Key獲取緩存元素
        System.out.println(e2);
        System.out.println(e2.getObjectValue());
         
        c.flush(); // 刷新緩存
        manager.shutdown(); // 關閉緩存管理器
	}

}

  

EhCache緩存框架的使用