由於要做一個產品,並想希望產品實現分布式,不得不研究下分布式緩衝。
緩衝的開源項目很多,通過測試,JCS配置及使用最為容易,所以就選用它做為產品緩衝管理器。
JCS是Apache的一個開源項目,項目網址:http://jakarta.apache.org/jcs/
實現步驟:
1、下載項目jar包,及依賴jar包
jcs-1.3.jar
commons-lang-2.3.jar
commons-collections-2.1.1.jar
concurrent-1.3.4.jar
2、JCS分布式配置
在你項目WEB-INF/classes下設定檔cache.ccf
內容如下:
jcs.default=LTCP
jcs.default.cache.attributes=org.apache.jcs.engine.CompositeCacheAttributes
jcs.default.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache
jcs.auxiliary.LTCP=org.apache.jcs.auxiliary.lateral.socket.tcp.LateralTCPCacheFactory
jcs.auxiliary.LTCP.attributes=org.apache.jcs.auxiliary.lateral.socket.tcp.TCPLateralCacheAttributes
jcs.auxiliary.LTCP.attributes.PutOnlyMode=true
jcs.auxiliary.LTCP.attributes.TcpListenerPort=1100
jcs.auxiliary.LTCP.attributes.UdpDiscoveryAddr=228.5.6.8
jcs.auxiliary.LTCP.attributes.UdpDiscoveryPort=1101
jcs.auxiliary.LTCP.attributes.UdpDiscoveryEnabled=true
以上配置實現了區域網路內組播形式的通訊,你可以配置多台伺服器,當一台更新緩衝時,其他幾台緩衝同時被通知更新,實現分布式緩衝需求。
3、代碼實現
實現代碼相當簡潔,附上我的緩衝管理類。
當其中一台機子實現addCache.updateCache.removeCache方法時,均會觸發緩衝同步事件。
附:
package com.framework.cache;
import org.apache.jcs.JCS;
/**
* 用途:緩衝管理器
*
* @author 顧偉民
* @date 2009-11-12
*/
public class CacheManager {
/**
* 系統緩衝體
*/
public static JCS CACHE;
/**
* 初始化緩衝管理器
* @autor 顧偉民
*/
public static void init() {
try {
CACHE = JCS.getInstance("SystemCache");
}
catch(Exception e) {
e.printStackTrace();
}
}
/**
* 新增緩衝
* @autor 顧偉民
*
* @param cacheKey 標識
* @param obj 緩衝對象
* @return true或false
*/
public static boolean addCache(String cacheKey, Object obj) {
try {
CACHE.put(cacheKey, obj);
return true;
}
catch(Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 更新緩衝
* @autor 顧偉民
*
* @param cacheKey 標識
* @param obj 緩衝對象
* @return true或false
*/
public static boolean updateCache(String cacheKey, Object obj) {
try {
if(CACHE.get(cacheKey)!=null) removeCache(cacheKey);
return addCache(cacheKey, obj);
}
catch(Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 刪除緩衝
* @autor 顧偉民
*
* @param key 標識
* @return true或false
*/
public static boolean removeCache(String cacheKey) {
try {
CACHE.remove(cacheKey);
return true;
}
catch(Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 擷取指定緩衝對象
* @autor 顧偉民
*
* @param key 標識
* @return Object 緩衝對象
*/
public static Object getCache(String cacheKey) {
try {
return CACHE.get(cacheKey);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
}