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的話,往往會報錯:

Java代碼 復制代碼  收藏代碼
  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有兩種獲得方法,一種是實例模式,一種是單例模式。這里我們用后面一種:

Java代碼 復制代碼  收藏代碼
  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的簡單例子:

Java代碼 復制代碼  收藏代碼
  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實例來操縱緩存了,主要的方法是

Java代碼 復制代碼  收藏代碼
  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工具包:

Java代碼 復制代碼  收藏代碼
  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來傳輸的話,需要把文件內容首先進行壓縮。

Java代碼 復制代碼  收藏代碼
  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來改變緩存內容

Java代碼 復制代碼  收藏代碼
  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));
	}
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM