最近再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的話,往往會報錯:
- 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)
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有兩種獲得方法,一種是實例模式,一種是單例模式。這里我們用后面一種:
-
- CacheManager.create();
- Cache cache = CacheManager.getInstance().getCache("staticResourceCache");
-
//CacheManager manager = new CacheManager("src/ehcache.xml");實例模式
CacheManager.create();//單例模式,默認讀取類路徑下的ehcache.xml作為配置文件
Cache cache = CacheManager.getInstance().getCache("staticResourceCache");
//staticResourceCache在ehcache.xml中提前定義了
ehcache.xml的簡單例子:
- 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>
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實例來操縱緩存了,主要的方法是
- 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工具包:
- 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);
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來傳輸的話,需要把文件內容首先進行壓縮。
- import java.util.zip.GZIPOutputStream;
- import jodd.io.FastByteArrayOutputStream;
- import jodd.io.StreamUtil;
-
- 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");
- }
-
- 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);
- }
- }
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來改變緩存內容
-
- 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));
- }
- });
//監控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));
}
});