JAVA緩存技術

最近再ITEYE上看到關於討論JAVA緩存技術的帖子比較多,本身不懂,因此上網大 概搜了下,找到一篇,暫做保存,後面若是有用到能夠參考。此爲轉貼,帖子來處:http://cogipard.info/articles /cache-static-files-with-jnotify-and-ehcache

介紹
JNotify:http://jnotify.sourceforge.net/,經過JNI技術,讓Java代碼能夠實時的監控制定文件夾內文件的變更信息,支持Linux/Windows/MacOS;
EHCache:http://ehcache.org/,一個普遍使用的Java緩存模塊,能夠作使用內存和文件完成緩存工做。
在Java Web項目中,爲了提升WEB應用的響應速度,能夠把經常使用的靜態文件(包括css,js和其餘各類圖片)提早讀入到內存緩存中,這樣能夠減小不少文件系統 的IO操做(這每每也是項目性能的瓶頸之一)。可是這麼作每每有一個弊端,那就是當實際的靜態文件發生改變的時候,緩存並不能獲得及時的刷新,形成了必定 的滯後現象。有些項目可能沒什麼問題,可是對於某些項目而言,必須解決這個問題。辦法基本有兩種,一種是另外開啓一個線程,不斷的掃描文件,和緩存的文件 作比較,肯定該文件時候修改,另外就是使用系統的API,來監控文件的改變。前面一種解決辦法缺點很明顯,費時費力,後面的辦法須要用到JNI,而且編寫 一些系統的本地庫函數,幸運的是,JNoify爲咱們作好了準備工做,直接拿來用就能夠了。

本文會簡單給出一個利用JNotify和EHCache實現靜態文件緩存的一個小例子。


JNotify的準備
在使用JNotify以前,你須要「安裝」一下JNotify。JNotify使用了JNI技術來調用系統的本地庫(Win下的是dll文件,Linux下是so文件),這些庫文件都已近包含在下載包中了。可是若是你直接使用JNotify的話,每每會報錯:

  1. BASH   
  2. java.lang.UnsatisfiedLinkError: no jnotify in java.library.path   
  3.     at java.lang.ClassLoader.loadLibrary(Unknown Source)   
  4.     at java.lang.Runtime.loadLibrary0(Unknown Source)   
  5.     at java.lang.System.loadLibrary(Unknown Source)   
  6.     at net.contentobjects.jnotify.win32.JNotify_win32.<clinit>(Unknown Source)   
  7.     at net.contentobjects.jnotify.win32.JNotifyAdapterWin32.<init>(Unknown Source)  
BASH
java.lang.UnsatisfiedLinkError: no jnotify in java.library.path
	at java.lang.ClassLoader.loadLibrary(Unknown Source)
	at java.lang.Runtime.loadLibrary0(Unknown Source)
	at java.lang.System.loadLibrary(Unknown Source)
	at net.contentobjects.jnotify.win32.JNotify_win32.<clinit>(Unknown Source)
	at net.contentobjects.jnotify.win32.JNotifyAdapterWin32.<init>(Unknown Source)


這是因爲jnotify找不到須要的dll或者其餘庫文件致使的,解決辦法是把jnotify壓縮包裏的庫文件放到java.library.path所指向的文件夾中,通常在windows下能夠放在[jre安裝目錄]/bin下便可。

java.library.path 的值能夠經過System.getProperty("java.library.path")查看,可是你即便在程序中經過 System.setProperty("java.library.path", "some/folder/path/contain/dll")來改變java.library.path的值,仍是沒法加載到對應的dll庫文件,原 因是JVM只在程序加載之初讀取java.library.path,之後再使用java.library.path的時候,用的都是最一開始加載到得那 個值。有人認爲只是一個bug,而且報告給了SUN(http://bugs.sun.com/bugdatabase /view_bug.do?bug_id=4280189)可是好像SUN不認爲這是一個BUG。
除了把dll文件放到[jre安裝目錄]/bin下,也能夠手動指定程序的啓動參數:
java -Djava.library.path=some/folder/path/contain/dll的方法來達到目的。

EHCache的基本使用方法
EHCache很是容易使用,首先咱們要得到一個CacheManager的實例。CacheManager有兩種得到方法,一種是實例模式,一種是單例模式。這裏咱們用後面一種:

  1. //CacheManager manager = new CacheManager("src/ehcache.xml");實例模式   
  2. CacheManager.create();//單例模式,默認讀取類路徑下的ehcache.xml做爲配置文件   
  3. Cache cache = CacheManager.getInstance().getCache("staticResourceCache");   
  4. //staticResourceCache在ehcache.xml中提早定義了  
//CacheManager manager = new CacheManager("src/ehcache.xml");實例模式
CacheManager.create();//單例模式,默認讀取類路徑下的ehcache.xml做爲配置文件
Cache cache = CacheManager.getInstance().getCache("staticResourceCache");
//staticResourceCache在ehcache.xml中提早定義了


ehcache.xml的簡單例子:

  1. ehcache.xml :   
  2. <?xml version="1.0" encoding="UTF-8"?>   
  3. <ehcache updateCheck="false" dynamicConfig="false">   
  4.     <diskStore path="java.io.tmpdir"/>   
  5.     <cache name="staticResourceCache"  
  6.         maxElementsInMemory="1000"  
  7.         timeToIdleSeconds="7200"  
  8.         timeToLiveSeconds="7200" >   
  9.     </cache>   
  10. </ehcache>  
ehcache.xml :
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" dynamicConfig="false">
	<diskStore path="java.io.tmpdir"/>
    <cache name="staticResourceCache"
		maxElementsInMemory="1000"
		timeToIdleSeconds="7200"
		timeToLiveSeconds="7200" >
    </cache>
</ehcache>


而後就可使用Cache實例來操縱緩存了,主要的方法是

  1. Cache.get(Object key),Cache.put(new Element(Object key, Object value)),Cache.remove(Object key)。  
Cache.get(Object key),Cache.put(new Element(Object key, Object value)),Cache.remove(Object key)。



緩存靜態文件
首先須要掃描包含靜態文件的文件夾,爲了方便咱們採用Jodd工具包:

  1. import jodd.io.findfile.FilepathScanner;   
  2. ...   
  3. FilepathScanner fs = new FilepathScanner(){   
  4.     @Override  
  5.     protected void onFile(File file) {   
  6.         cacheStatic(file);//緩存文件的函數,實現見後面   
  7.     }   
  8. };   
  9. fs.includeDirs(true).recursive(true).includeFiles(true);   
  10. fs.scan(Configurations.THEMES_PATH);//掃描包含靜態文件的文件夾  
import jodd.io.findfile.FilepathScanner;
...
FilepathScanner fs = new FilepathScanner(){
	@Override
	protected void onFile(File file) {
		cacheStatic(file);//緩存文件的函數,實現見後面
	}
};
fs.includeDirs(true).recursive(true).includeFiles(true);
fs.scan(Configurations.THEMES_PATH);//掃描包含靜態文件的文件夾


通常來講,若是客戶端瀏覽器接受GZip格式的文件的話,GZip壓縮可讓傳輸的數據大幅度減小,因此考慮對某些緩存的靜態文件提早進行GZip壓縮。把讀取到的靜態文件內容緩存到Cache裏,若是靜態文件時能夠用GZip來傳輸的話,須要把文件內容首先進行壓縮。

  1. import java.util.zip.GZIPOutputStream;//JDK自帶的GZip壓縮工具   
  2. import jodd.io.FastByteArrayOutputStream;//GZip輸出的是字節流   
  3. import jodd.io.StreamUtil;//JODD的工具類   
  4.     
  5. private static void cacheStatic(File file){   
  6.     if(!isStaticResource(file.getAbsolutePath()))   
  7.         return;   
  8.     String uri = toURI(file.getAbsolutePath());//生成一個文件標識   
  9.     FileInputStream in = null;   
  10.     StringBuilder builder = new StringBuilder();   
  11.     try {   
  12.         in = new FileInputStream(file);   
  13.         BufferedReader br = new BufferedReader(   
  14.                 new InputStreamReader(in, StringPool.UTF_8));   
  15.         String strLine;   
  16.         while ((strLine = br.readLine()) != null)   {   
  17.             builder.append(strLine);   
  18.             builder.append("\n");//!important   
  19.         }   
  20.     
  21.         FastByteArrayOutputStream bao = new FastByteArrayOutputStream();   
  22.         GZIPOutputStream go = new GZIPOutputStream(bao);   
  23.         go.write(builder.toString().getBytes());   
  24.         go.flush();   
  25.         go.close();   
  26.         cache.put(new Element(uri, bao.toByteArray()));//緩存文件的字節流   
  27.     } catch (FileNotFoundException e) {   
  28.         e.printStackTrace();   
  29.     } catch (UnsupportedEncodingException e) {   
  30.         e.printStackTrace();   
  31.     } catch (IOException e) {   
  32.         e.printStackTrace();   
  33.     } finally {   
  34.         StreamUtil.close(in);   
  35.     }   
  36. }  
import java.util.zip.GZIPOutputStream;//JDK自帶的GZip壓縮工具
import jodd.io.FastByteArrayOutputStream;//GZip輸出的是字節流
import jodd.io.StreamUtil;//JODD的工具類
 
private static void cacheStatic(File file){
	if(!isStaticResource(file.getAbsolutePath()))
		return;
	String uri = toURI(file.getAbsolutePath());//生成一個文件標識
	FileInputStream in = null;
	StringBuilder builder = new StringBuilder();
	try {
		in = new FileInputStream(file);
		BufferedReader br = new BufferedReader(
				new InputStreamReader(in, StringPool.UTF_8));
		String strLine;
		while ((strLine = br.readLine()) != null)   {
			builder.append(strLine);
			builder.append("\n");//!important
		}
 
		FastByteArrayOutputStream bao = new FastByteArrayOutputStream();
		GZIPOutputStream go = new GZIPOutputStream(bao);
		go.write(builder.toString().getBytes());
		go.flush();
		go.close();
		cache.put(new Element(uri, bao.toByteArray()));//緩存文件的字節流
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		StreamUtil.close(in);
	}
}


當文件改變的時候,使用JNotify來改變緩存內容

  1. //監控Configurations.THEMES_PATH指向的文件夾   
  2. JNotify.addWatch(Configurations.THEMES_PATH,    
  3.         JNotify.FILE_CREATED  |    
  4.         JNotify.FILE_DELETED  |    
  5.         JNotify.FILE_MODIFIED |    
  6.         JNotify.FILE_RENAMED,    
  7.         true,  new JNotifyListener(){   
  8.     
  9.     @Override  
  10.     public void fileCreated(int wd,   
  11.             String rootPath, String name) {   
  12.         cacheStatic(new File(rootPath+name));//更新緩存   
  13.     }   
  14.     
  15.     @Override  
  16.     public void fileDeleted(int wd,   
  17.             String rootPath, String name) {   
  18.         cache.remove(toURI(rootPath)+name);//刪除緩存條目   
  19.     }   
  20.     
  21.     @Override  
  22.     public void fileModified(int wd,   
  23.             String rootPath, String name) {   
  24.         cacheStatic(new File(rootPath+name));   
  25.     }   
  26.     
  27.     @Override  
  28.     public void fileRenamed(int wd,   
  29.             String rootPath, String oldName,   
  30.             String newName) {   
  31.         cache.remove(toURI(rootPath)+oldName);   
  32.         cacheStatic(new File(rootPath+newName));   
  33.     }   
  34. });  
//監控Configurations.THEMES_PATH指向的文件夾
JNotify.addWatch(Configurations.THEMES_PATH, 
		JNotify.FILE_CREATED  | 
		JNotify.FILE_DELETED  | 
		JNotify.FILE_MODIFIED | 
		JNotify.FILE_RENAMED, 
		true,  new JNotifyListener(){
 
	@Override
	public void fileCreated(int wd,
			String rootPath, String name) {
		cacheStatic(new File(rootPath+name));//更新緩存
	}
 
	@Override
	public void fileDeleted(int wd,
			String rootPath, String name) {
		cache.remove(toURI(rootPath)+name);//刪除緩存條目
	}
 
	@Override
	public void fileModified(int wd,
			String rootPath, String name) {
		cacheStatic(new File(rootPath+name));
	}
 
	@Override
	public void fileRenamed(int wd,
			String rootPath, String oldName,
			String newName) {
		cache.remove(toURI(rootPath)+oldName);
		cacheStatic(new File(rootPath+newName));
	}
});
相關文章
相關標籤/搜索