非常感谢http://blog.csdn.net/lfsfxy9/article/details/22692249
缓存技术学习 https://www.itkc8.com
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?
- /*
- * @copyright(disclaimer)
- *
- * Licensed Materials - Property of IBM
- * (C) Copyright IBM Corp. 2010 All Rights Reserved.
- *
- * The source code for this program is not published or otherwise
- * divested of its trade secrets, irrespective of what has been
- * deposited with the U.S. Copyright Office.
- *
- * @endCopyright
- */
- package com.jizg.common.cache;
- import java.io.Serializable;
- import org.apache.jcs.JCS;
- import org.apache.jcs.access.exception.CacheException;
- import org.apache.jcs.engine.CacheElement;
- import org.apache.log4j.Logger;
- /**
- *
- *
- * @version $Rev: 1046 $ $Date: 2012-01-12 17:41:24 +0800 $
- */
- public class CacheWrapper {
- private final Logger logger = Logger.getLogger(CacheWrapper.class);
- /**
- * Cache实例
- *
- */
- public JCS cache;
- public CacheWrapper(JCS cache) {
- this.cache = cache;
- }
- public void put(String key, Serializable value) {
- try {
- cache.put(key, value);
- } catch (CacheException e) {
- logger.error("Method put(String key, Serializable value),Put Element to the Cache Error,Key is ["+ key + "] Val is [" + value + "]", e);
- }
- }
- public void put(String key, Object value) {
- try {
- cache.put(key, value);
- } catch (CacheException e) {
- logger.error("Method put(String key, Serializable value),Put Element to the Cache Error,Key is [" + key + "] Val is [" + value + "]", e);
- }
- }
- public Serializable get(String key) {
- CacheElement cacheElement = (CacheElement) cache.getCacheElement(key);
- if (null != cacheElement) {
- Serializable serializable = cacheElement.val;
- return serializable;
- }
- return null;
- }
- public Object getObject(String key) {
- CacheElement cacheElement = (CacheElement) cache.getCacheElement(key);
- if (null != cacheElement) {
- Object object = cacheElement.val;
- return object;
- }
- return null;
- }
- public boolean remove(String key) {
- try {
- cache.remove(key);
- return true;
- } catch (CacheException e) {
- logger.error("Method remove(String key),Not remove CacheElement from the Cache by Key is["+ key + "], remove Error", e);
- return false;
- }
- }
- }
CacheUtils.java
[java] view plaincopyprint?
- /*
- * @copyright(disclaimer)
- *
- * Licensed Materials - Property of IBM
- * (C) Copyright IBM Corp. 2013 All Rights Reserved.
- *
- * The source code for this program is not published or otherwise
- * divested of its trade secrets, irrespective of what has been
- * deposited with the U.S. Copyright Office.
- *
- * @endCopyright
- */
- package com.jizg.common.cache;
- import java.util.HashMap;
- import org.apache.jcs.JCS;
- import org.apache.jcs.access.exception.CacheException;
- import org.apache.log4j.Logger;
- import com.jizg.common.scheduler.SchedulerUtil;
- /**
- *
- *
- * @version $Rev$ $Date$
- */
- public class CacheUtils {
- public static Logger logger = Logger.getLogger(CacheUtils.class);
- public static HashMap<String, CacheWrapper> cacheWrapperMap = new HashMap<String, CacheWrapper>();
- public static String cacheName = "testCache1";
- public static void createCache(String cacheName){
- if(!cacheWrapperMap.containsKey(cacheName)){
- JCS cache = null;
- try {
- cache = JCS.getInstance(cacheName);
- } catch (CacheException e) {
- logger.error("获取缓存实例出错:"+e.getMessage());
- }
- cacheWrapperMap.put(cacheName, new CacheWrapper(cache));
- logger.info("put "+ cacheName+" in cacheWrapperMap("+cacheWrapperMap+")");
- }else{
- logger.info(cacheName+" cacheObj has existed.");
- }
- }
- public static CacheWrapper getCacheWrapperByName(String name){
- if(cacheWrapperMap.containsKey(name)){
- logger.info("取到缓存对象,"+name);
- return cacheWrapperMap.get(name);
- }else{
- logger.error("没有缓存对象,"+name);
- return null;
- }
- }
- public static void initCache(String cacheName){
- CacheWrapper cacheWrapper = cacheWrapperMap.get(cacheName);
- String key = "test";
- String value ="jizg";
- for (int i = 0; i < 1000; i++) {
- cacheWrapper.put(key+(i+1), value+(i+1));
- // logger.info("put key:"+key+i+", value:"+value+i);
- }
- logger.info("init cacheWarpper "+cacheName+" end !!!");
- }
- /**
- * 缓存测试入口
- * @param args
- */
- public static void main(String[] args) {
- //创建缓存实例
- createCache(cacheName);
- //初始化缓存数据
- initCache(cacheName);
- CacheWrapper cache = CacheUtils.getCacheWrapperByName(CacheUtils.cacheName);
- System.out.println("test100:"+cache.get("test100"));
- System.out.println("test300:"+cache.get("test998"));
- System.out.println("test1000:"+cache.get("test999"));
- //启动定时任务-定时随机获取缓存数据
- // schedulerTestCacheSafeLifeSecond();
- }
- /**
- * 初始化定时任务
- */
- static void schedulerTestCacheSafeLifeSecond(){
- SchedulerUtil.initScheduleTestCache();
- }
- }
TestCacheSafeLifeSecondTask.java
[java] view plaincopyprint?
- package com.jizg.common.scheduler;
- import java.util.Random;
- import java.util.TimerTask;
- import org.apache.log4j.Logger;
- import com.jizg.common.cache.CacheUtils;
- import com.jizg.common.cache.CacheWrapper;
- /**
- * 定时读写Cache类
- *
- * @version $Rev$ $Date$
- */
- public class TestCacheSafeLifeSecondTask extends TimerTask {
- private Logger logger = Logger.getLogger(TestCacheSafeLifeSecondTask.class);
- private static int runNumber = 1;
- private static TestCacheSafeLifeSecondTask initcachetask = null;
- public static TestCacheSafeLifeSecondTask getInstance(long nextTimelong) {
- if (initcachetask == null) {
- initcachetask = new TestCacheSafeLifeSecondTask();
- }
- return initcachetask;
- }
- @Override
- public void run() {
- CacheWrapper cache = CacheUtils.getCacheWrapperByName(CacheUtils.cacheName);
- Random random = new Random();
- String cacheKey = "test"+random.nextInt(1000);
- logger.info(runNumber+" 随机取得cache key:"+cacheKey+" ,cache value:"+cache.get(cacheKey));
- if(runNumber==4){
- //重新初始化缓存对象
- CacheUtils.initCache(CacheUtils.cacheName);
- }
- runNumber+=1;
- }
- }
SchedulerUtil.java
[java] view plaincopyprint?
- /*
- * @copyright(disclaimer)
- *
- * Licensed Materials - Property of IBM
- * (C) Copyright IBM Corp. 2013 All Rights Reserved.
- *
- * The source code for this program is not published or otherwise
- * divested of its trade secrets, irrespective of what has been
- * deposited with the U.S. Copyright Office.
- *
- * @endCopyright
- */
- package com.jizg.common.scheduler;
- import java.util.Random;
- import java.util.Timer;
- import org.apache.log4j.Logger;
- /**
- * Scheduler 定时任务
- *
- * @version $Rev$ $Date$
- */
- public class SchedulerUtil {
- public static Logger logger = Logger.getLogger(SchedulerUtil.class);
- private static Timer initSchedulerTestTimer = null;
- public static void initScheduleTestCache() {
- logger.info(" initScheduleTestCache ");
- initSchedulerTestTimer = new Timer("INIT_SCHEDULER_TIMER_TASK_TEST_CACHE_JOB", false);
- long nextTime = 60 * 1000; //定义定时任务的时间间隔
- TestCacheSafeLifeSecondTask myTimeTask = TestCacheSafeLifeSecondTask.getInstance(nextTime);
- //立即执行定时任务,每隔nextTime间隔执行一次
- initSchedulerTestTimer.scheduleAtFixedRate(myTimeTask, 0, nextTime);
- }
- }
运行结果:
[plain] view plaincopyprint?
- INFO[03/31 21:03:30][main](CacheUtils.java:45) - put testCache1 in cacheWrapperMap({testCache1=com.jizg.common.cache.CacheWrapper@18a61164})
- INFO[03/31 21:03:30][main](CacheUtils.java:69) - init cacheWarpper testCache1 end !!!
- INFO[03/31 21:03:30][main](CacheUtils.java:53) - 取到缓存对象,testCache1
- test100:jizg100
- test999:jizg999
- 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。
缓存技术学习 https://www.itkc8.com