使用JCS快速搭建缓存环境
</div>
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; } }
</div>
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"); } }
</div>
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!