使用JCS快速搭建缓存环境

来源:互联网 发布:谁有淘宝免单的群 编辑:程序博客网 时间:2024/06/08 13:38

JCSJakarta的项目Turbine的子项目。它是一个复合式的缓冲工具。可以将对象缓冲到内存、硬盘。具有缓冲对象时间过期设定。还可以通过JCS构建具有缓冲的分布式构架,以实现高性能的应用。对于一些需要频繁访问而每访问一次都非常消耗资源的对象,可以临时存放在缓冲区中,这样可以提高服务的性能。而JCS正是一个很好的缓冲工具。缓冲工具对于读操作远远多于写操作的应用性能提高非常显著。


一、理解缓存的三个核心概念

Elements : JCS是一个对象缓存,能放置一些对象或是”elements”并通过key来访问它们,很像一个hashtable。可以想象JCS是一个能过Name来获取的hashtables的集合。

Regions : 每一个hashtables都被称做“region”,每一个region都能被独立于其他regions配置。例如,可以有一个称做城市的region,缓存了一些定期被改变的城市对象。可以定义一个region被叫做产品,缓存一些定期改变的产品数据。将可以配置易变的产品的regionelements 过期时间要快于cityregion

Auxiliaries : Auxiliariesregion能用的插件选项。核心的AuxiliariesIndexedDisk CacheTCPLateral CacheRemoteCache Server。例如,磁盘缓存允许当内存达到阈值后把缓存对象交换到硬上。


二、下载JCS

可以从JCS官网下载JCS,可以查看JCS相关的文档。


三、获取JCS依赖的Jar

JCS必备的Jar有两个,分别是jcs-1.3.jarconcurrent.jar,这两个jar都可以从官网下载。除此之外,我们最好也把Log4j所支持的jar包下载,因为那样方便我们打印一些日志。


四、配置JCS

src目录下创建cache.ccf配置文件,将下面的内容Copy到文件中。

# DEFAULT  CACHE REGION

jcs.default=

jcs.default.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes

jcs.default.cacheattributes.MaxObjects=1000

jcs.default.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache

这里需要注意的是,等号“=”之后不要留空格,否则cache.ccf不会识别。


五、开始使用JCS编程

5.1创建CacheWrapper类,使用其添加对象、获取对象和移除对象。

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;    }           }

5.2创建CacheFactory类,使用工厂管理缓存对象,用以初始化缓存和清理缓存。

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");    }}


5.3创建测试类TestCache,测试刚才的缓存对象。

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");    }}