使用JCS快速搭建緩存環境
</td>
</tr>
</tbody>
</table>
package com.favccxx.favjcs;
import org.apache.jcs.JCS;
import org.apache.jcs.access.exception.CacheException;
import org.apache.jcs.engine.CacheElement;
public class CacheWrapper {
public JCS jcsCache = null;
public CacheWrapper(JCS cache){
this.jcsCache = cache;
}
public void put(String key , Object value){
try{
jcsCache.put(key, value);
}catch(CacheException e){
e.printStackTrace();
}
}
public Object get(String key){
CacheElement cacheElement = (CacheElement) jcsCache.getCacheElement(key);
if (null != cacheElement) {
Object object = cacheElement.val;
return object;
}
return null;
}
}package com.favccxx.favjcs;
import java.util.HashMap;
import java.util.Map;
import org.apache.jcs.JCS;
import org.apache.jcs.access.exception.CacheException;
import org.apache.log4j.Logger;
public class CacheFactory {
private static Logger logger = Logger.getLogger(CacheFactory.class);
private static Map<String, CacheWrapper> hashMapWrapper = new HashMap<String, CacheWrapper>();
/**
* 獲取一個名稱為cacheName的緩存對象;如果不存在,返回null
* @param cacheName
* @return
*/
public static CacheWrapper getCacheWrapper(String cacheName){
logger.debug("Get CacheWrapper, The cacheName is : " + cacheName);
return hashMapWrapper.get(cacheName);
}
/**
* 清理所有的緩存
*/
public static void clearCache(){
Object[] cacheArray = hashMapWrapper.keySet().toArray();
for(int i=0, l=cacheArray.length; i<l; i++){
try {
String cacheName = cacheArray[i].toString();
logger.debug("The cache is below to clear, And the name is : " + cacheName);
CacheWrapper cacheWrapper = hashMapWrapper.get(cacheName);
cacheWrapper.jcsCache.clear();
} catch (CacheException e) {
logger.debug("Clear Cache Error!");
e.printStackTrace();
}
}
}
/**
* 獲取一個名稱為cacheName的緩存對象;如果不存在,則創建一個新的緩存對象
* @param cacheName
* @return
*/
private static CacheWrapper createCacheWrapper(String cacheName){
JCS cache = null;
try{
cache = JCS.getInstance(cacheName);
return new CacheWrapper(cache);
}catch(CacheException e){
return null;
}
}
/**
* 創建緩存對象
* @param cacheName
*/
private static void createHashMapWrapper(String cacheName){
hashMapWrapper.put(cacheName, createCacheWrapper(cacheName));
}
/**
* 初始化緩存對象
*/
public static void initCache(){
logger.debug("By Start initCache Method, We create all the Cache Object");
createHashMapWrapper("coolBoyCache");
// createHashMapWrapper("beautifulGirl");
}
}package com.favccxx.favjcs.web;
import com.favccxx.favjcs.CacheFactory;
public class TestCache {
/**
* @param args
*/
public static void main(String[] args) {
CacheFactory.initCache();
CacheFactory.getCacheWrapper("coolBoy");
}
} 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
相關經驗相關資訊 |