JCS的学习与应用三:内存缓存应用

来源:互联网 发布:mac清楚最近使用记录 编辑:程序博客网 时间:2024/05/19 03:43

非常感谢http://blog.csdn.net/lfsfxy9/article/details/22692249


       JCS内存缓存应用

         前面重点讲了配置文件中常见的缓存配置项,接下来我们结合实例来看看单一的使用内存缓存进行读写操作等。精简配置如下:


cache.ccf

# optional region "testCache1" specific configuration settings
jcs.region.testCache1=
jcs.region.testCache1.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes
jcs.region.testCache1.cacheattributes.MaxObjects=1000
jcs.region.testCache1.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache
jcs.region.testCache1.cacheattributes.UseMemoryShrinker=false
#jcs.region.testCache1.elementattributes=org.apache.jcs.engine.ElementAttributes
jcs.region.testCache1.elementattributes.IsEternal=false
jcs.region.testCache1.elementattributes.MaxLifeSeconds=180
jcs.region.testCache1.elementattributes.IsSpool=false
jcs.region.testCache1.elementattributes.IsLateral=false
fjcs.region.testCache1.elementattributes.IsRemote=false
不包括其他辅助缓存的配置。

       示例代码分为缓存类和定时任务类,缓存类用来创建和实例化缓存队列,定时任务类用来定时测试缓存失效的情况等等。

CacheWrapper.java

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * @copyright(disclaimer) 
  3.  * 
  4.  * Licensed Materials - Property of IBM 
  5.  * (C) Copyright IBM Corp. 2010  All Rights Reserved. 
  6.  * 
  7.  * The source code for this program is not published or otherwise 
  8.  * divested of its trade secrets, irrespective of what has been 
  9.  * deposited with the U.S. Copyright Office. 
  10.  * 
  11.  * @endCopyright 
  12.  */  
  13. package com.jizg.common.cache;  
  14.   
  15. import java.io.Serializable;  
  16.   
  17. import org.apache.jcs.JCS;  
  18. import org.apache.jcs.access.exception.CacheException;  
  19. import org.apache.jcs.engine.CacheElement;  
  20. import org.apache.log4j.Logger;  
  21. /** 
  22.  *  
  23.  *  
  24.  * @version $Rev: 1046 $ $Date: 2012-01-12 17:41:24 +0800 $ 
  25.  */  
  26. public class CacheWrapper {  
  27.     private final Logger logger = Logger.getLogger(CacheWrapper.class);  
  28.       
  29.     /** 
  30.      * Cache实例 
  31.      *  
  32.      */  
  33.     public JCS cache;  
  34.   
  35.     public CacheWrapper(JCS cache) {  
  36.         this.cache = cache;  
  37.     }  
  38.   
  39.     public void put(String key, Serializable value) {  
  40.         try {  
  41.             cache.put(key, value);  
  42.         } catch (CacheException e) {  
  43.             logger.error("Method put(String key, Serializable value),Put Element to the Cache Error,Key is ["+ key + "] Val is [" + value + "]", e);  
  44.         }  
  45.     }  
  46.   
  47.     public void put(String key, Object value) {  
  48.         try {  
  49.             cache.put(key, value);  
  50.         } catch (CacheException e) {  
  51.             logger.error("Method put(String key, Serializable value),Put Element to the Cache Error,Key is [" + key + "] Val is [" + value + "]", e);  
  52.         }  
  53.     }  
  54.   
  55.     public Serializable get(String key) {  
  56.         CacheElement cacheElement = (CacheElement) cache.getCacheElement(key);  
  57.         if (null != cacheElement) {  
  58.             Serializable serializable = cacheElement.val;  
  59.             return serializable;  
  60.         }  
  61.         return null;  
  62.     }  
  63.   
  64.     public Object getObject(String key) {  
  65.         CacheElement cacheElement = (CacheElement) cache.getCacheElement(key);  
  66.         if (null != cacheElement) {  
  67.             Object object = cacheElement.val;  
  68.             return object;  
  69.         }  
  70.         return null;  
  71.     }  
  72.   
  73.     public boolean remove(String key) {  
  74.         try {  
  75.             cache.remove(key);  
  76.             return true;  
  77.         } catch (CacheException e) {  
  78.             logger.error("Method remove(String key),Not remove CacheElement from the Cache by Key is["+ key + "], remove Error", e);  
  79.             return false;  
  80.         }  
  81.     }  
  82.   
  83. }  

CacheUtils.java
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * @copyright(disclaimer) 
  3.  * 
  4.  * Licensed Materials - Property of IBM 
  5.  * (C) Copyright IBM Corp. 2013  All Rights Reserved. 
  6.  * 
  7.  * The source code for this program is not published or otherwise 
  8.  * divested of its trade secrets, irrespective of what has been 
  9.  * deposited with the U.S. Copyright Office. 
  10.  * 
  11.  * @endCopyright 
  12.  */  
  13. package com.jizg.common.cache;  
  14.   
  15. import java.util.HashMap;  
  16.   
  17. import org.apache.jcs.JCS;  
  18. import org.apache.jcs.access.exception.CacheException;  
  19. import org.apache.log4j.Logger;  
  20.   
  21. import com.jizg.common.scheduler.SchedulerUtil;  
  22.   
  23.   
  24.   
  25. /** 
  26.  *  
  27.  * 
  28.  * @version $Rev$ $Date$ 
  29.  */  
  30. public class CacheUtils {  
  31.   
  32.     public static Logger logger = Logger.getLogger(CacheUtils.class);  
  33.     public static HashMap<String, CacheWrapper> cacheWrapperMap = new HashMap<String, CacheWrapper>();  
  34.     public static String cacheName = "testCache1";  
  35.       
  36.     public static void createCache(String cacheName){  
  37.         if(!cacheWrapperMap.containsKey(cacheName)){  
  38.             JCS cache = null;  
  39.             try {  
  40.                 cache = JCS.getInstance(cacheName);  
  41.             } catch (CacheException e) {  
  42.                 logger.error("获取缓存实例出错:"+e.getMessage());  
  43.             }  
  44.             cacheWrapperMap.put(cacheName, new CacheWrapper(cache));  
  45.             logger.info("put "+ cacheName+" in cacheWrapperMap("+cacheWrapperMap+")");  
  46.         }else{  
  47.             logger.info(cacheName+" cacheObj has existed.");  
  48.         }  
  49.     }  
  50.       
  51.     public static CacheWrapper getCacheWrapperByName(String name){  
  52.         if(cacheWrapperMap.containsKey(name)){  
  53.             logger.info("取到缓存对象,"+name);  
  54.             return cacheWrapperMap.get(name);  
  55.         }else{  
  56.             logger.error("没有缓存对象,"+name);  
  57.             return null;  
  58.         }  
  59.     }  
  60.       
  61.     public static void initCache(String cacheName){  
  62.         CacheWrapper cacheWrapper = cacheWrapperMap.get(cacheName);  
  63.         String key = "test";  
  64.         String value ="jizg";  
  65.         for (int i = 0; i < 1000; i++) {  
  66.               cacheWrapper.put(key+(i+1), value+(i+1));  
  67. //            logger.info("put key:"+key+i+", value:"+value+i);  
  68.         }  
  69.         logger.info("init cacheWarpper "+cacheName+" end !!!");  
  70.     }  
  71.       
  72.     /** 
  73.      * 缓存测试入口 
  74.      * @param args 
  75.      */  
  76.     public static void main(String[] args) {  
  77.         //创建缓存实例  
  78.         createCache(cacheName);  
  79.           
  80.         //初始化缓存数据  
  81.         initCache(cacheName);  
  82.   
  83.         CacheWrapper cache = CacheUtils.getCacheWrapperByName(CacheUtils.cacheName);  
  84.         System.out.println("test100:"+cache.get("test100"));  
  85.         System.out.println("test300:"+cache.get("test998"));  
  86.         System.out.println("test1000:"+cache.get("test999"));  
  87.   
  88.         //启动定时任务-定时随机获取缓存数据  
  89. //        schedulerTestCacheSafeLifeSecond();  
  90.     }  
  91.       
  92.     /** 
  93.      * 初始化定时任务 
  94.      */  
  95.     static void schedulerTestCacheSafeLifeSecond(){  
  96.         SchedulerUtil.initScheduleTestCache();  
  97.     }  
  98.       
  99. }  

TestCacheSafeLifeSecondTask.java

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package com.jizg.common.scheduler;  
  2.   
  3. import java.util.Random;  
  4. import java.util.TimerTask;  
  5.   
  6. import org.apache.log4j.Logger;  
  7.   
  8. import com.jizg.common.cache.CacheUtils;  
  9. import com.jizg.common.cache.CacheWrapper;  
  10.   
  11. /** 
  12.  * 定时读写Cache类 
  13.  *   
  14.  * @version $Rev$ $Date$ 
  15.  */  
  16. public class TestCacheSafeLifeSecondTask extends TimerTask {  
  17.     private Logger logger = Logger.getLogger(TestCacheSafeLifeSecondTask.class);  
  18.     private static int runNumber = 1;  
  19.     private static TestCacheSafeLifeSecondTask initcachetask = null;  
  20.   
  21.     public static TestCacheSafeLifeSecondTask getInstance(long nextTimelong) {  
  22.         if (initcachetask == null) {  
  23.             initcachetask = new TestCacheSafeLifeSecondTask();  
  24.         }  
  25.         return initcachetask;  
  26.     }  
  27.   
  28.     @Override  
  29.     public void run() {  
  30.        CacheWrapper cache = CacheUtils.getCacheWrapperByName(CacheUtils.cacheName);  
  31.        Random random = new Random();   
  32.        String cacheKey = "test"+random.nextInt(1000);  
  33.          
  34.        logger.info(runNumber+"  随机取得cache key:"+cacheKey+" ,cache value:"+cache.get(cacheKey));  
  35.        if(runNumber==4){  
  36.            //重新初始化缓存对象  
  37.            CacheUtils.initCache(CacheUtils.cacheName);  
  38.        }  
  39.        runNumber+=1;  
  40.     }  
  41. }  

SchedulerUtil.java

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * @copyright(disclaimer) 
  3.  * 
  4.  * Licensed Materials - Property of IBM 
  5.  * (C) Copyright IBM Corp. 2013  All Rights Reserved. 
  6.  * 
  7.  * The source code for this program is not published or otherwise 
  8.  * divested of its trade secrets, irrespective of what has been 
  9.  * deposited with the U.S. Copyright Office. 
  10.  * 
  11.  * @endCopyright 
  12.  */  
  13. package com.jizg.common.scheduler;  
  14.   
  15. import java.util.Random;  
  16. import java.util.Timer;  
  17.   
  18. import org.apache.log4j.Logger;  
  19.   
  20.   
  21. /** 
  22.  * Scheduler 定时任务 
  23.  * 
  24.  * @version $Rev$ $Date$ 
  25.  */  
  26. public class SchedulerUtil {  
  27.     public static Logger logger = Logger.getLogger(SchedulerUtil.class);  
  28.     private static Timer initSchedulerTestTimer = null;  
  29.   
  30.     public static void initScheduleTestCache() {  
  31.         logger.info(" initScheduleTestCache ");  
  32.         initSchedulerTestTimer = new Timer("INIT_SCHEDULER_TIMER_TASK_TEST_CACHE_JOB"false);  
  33.           
  34.         long nextTime = 60 * 1000;  //定义定时任务的时间间隔  
  35.         TestCacheSafeLifeSecondTask myTimeTask = TestCacheSafeLifeSecondTask.getInstance(nextTime);  
  36.           
  37.         //立即执行定时任务,每隔nextTime间隔执行一次  
  38.         initSchedulerTestTimer.scheduleAtFixedRate(myTimeTask, 0, nextTime);   
  39.           
  40.     }  
  41.       
  42. }  


运行结果:
[plain] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1.  INFO[03/31 21:03:30][main](CacheUtils.java:45) - put testCache1 in cacheWrapperMap({testCache1=com.jizg.common.cache.CacheWrapper@18a61164})  
  2.  INFO[03/31 21:03:30][main](CacheUtils.java:69) - init cacheWarpper testCache1 end !!!  
  3.  INFO[03/31 21:03:30][main](CacheUtils.java:53) - 取到缓存对象,testCache1  
  4. test100:jizg100  
  5. test999:jizg999  
  6. test1000:jizg1000  

       使用定时任务可以定时测试缓存数据是否存在,并针对cache.ccf中一些配置项进行验证,比如缓存有效期等。还需要注意,配置文件中配置的缓存数量要尽量大一些,不能小于我们实际put进去的数量,否则返回给你的只会是赤果果的null。

      其实,我们写代码的时候也常会用静态变量Map来存储一些常量或者不常改但常用的一些数据,每当我们停止server或者关闭进程的时候,静态Map就会自动销毁回收掉。JCS也可以算是这样一个更复杂、易用性更好、抽象层次更高的Map,内置了一些缓存属性、算法而已。


     另,示例代码需要引入commons-logging-1.1.1.jar、concurrent-1.0.jar、commons-collections-3.2.1.jar、commons-lang3-3.1.jar、jcs-1.3.jar。



0 0
原创粉丝点击