objectcachemanager.java

来自「Speedframework--基于类型元数据的羽量级ORM.完全基于Java类」· Java 代码 · 共 132 行

JAVA
132
字号
package org.speedframework.cache;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.speedframework.util.PropertyUtil;

/**
 * 对象缓存管理
 * 
 * @author 程伟杰 13926047208
 * 
 */
public class ObjectCacheManager {

	private static CachePool cp = null;
	static {
		try {
			if (cp != null) {
				cp = CacheManageProxy.startCache();
			}
		} catch (Exception ex) {
			throw new RuntimeException("Fail to start Cache", ex);
		}
	}

	/**
	 * 存放对象到对列中
	 * 
	 * @param region
	 * @param key
	 * @param value
	 * @throws Exception
	 */
	public static Object save(String region, Object key, Object source)
			throws Exception {
		return saveOrUpdate(region, key, source);

	}

	/**
	 * 获取对象队列中的对象
	 * 
	 * @param region
	 * @param key
	 * @throws Exception
	 */
	public static Object get(String region, Object key) throws Exception {
		Map queue = getQueueOfObject(region);
		Object reObj = null;

		if (queue.containsKey(key)) {
			reObj = queue.get(key);
		}

		return reObj;

	}

	/**
	 * 删除对象队列中对象
	 * 
	 * @param region
	 * @param key
	 * @throws Exception
	 */
	public static void remove(String region, Object key) throws Exception {
		Map queue = getQueueOfObject(region);

		if (queue.containsKey(key)) {
			queue.remove(key);
		}

	}

	/**
	 * 更新队列中的对象
	 * 
	 * @param region
	 * @param key
	 * @param source
	 * @throws Exception
	 */
	public static Object update(String region, Object key, Object source)
			throws Exception {
		return saveOrUpdate(region, key, source);

	}

	/**
	 * 缓存队列集合
	 * 
	 * @param region
	 * @return
	 * @throws Exception
	 */
	private static Map getQueueOfObject(String region) throws Exception {
		Map queue = (Map) cp.get(region);
		if (queue == null) {
			queue = Collections.synchronizedMap(new LinkedHashMap(100));
			cp.put(region, queue);
			getQueueOfObject(region);
		}
		return queue;

	}

	/**
	 * 插入更新方法
	 * 
	 * @param region
	 * @param key
	 * @param source
	 * @return
	 * @throws Exception
	 */
	private static Object saveOrUpdate(String region, Object key, Object source)
			throws Exception {
		Map queue = getQueueOfObject(region);
		Object old = null;
		if (queue.containsKey(key)) {
			old = queue.get(key);
			PropertyUtil.copyProperties(old, source);
		} else {
			queue.put(key, source);
		}

		return source;
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?