JAVA內存緩存使用,timer+map超時緩存。模擬redis、memcached

說起緩存,我們總是充滿敬意,介於程序與數據庫之間,緩解數據庫負載壓力,以內存爲代價,百倍提升程序性能。然而,內存是廉價的,只要不存儲大數據,基本也是可以接受的。

功能點:緩存key-value鍵值存儲、緩存過期時間

適用範圍:小程序、小項目、小數據存儲。高頻訪問數據存儲。單機非集羣數據存儲。

緩存代碼類:

package org.coody.framework.core.cache;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @className:CacheHandler
 * @description:緩存操作類,對緩存進行管理,清除方式採用Timer定時的方式
 * @creater:Coody
 * @creatTime:2014年5月7日 上午9:18:54 @remark:
 * @version
 */
@SuppressWarnings("unchecked")
public class LocalCache {
	// private static final long SECOND_TIME = 1000;//默認過期時間 20秒
	// private static final int DEFUALT_VALIDITY_TIME = 20;//默認過期時間 20秒
	private static final Timer timer;
	private static final ConcurrentHashMap<String, Object> map;
	static Object mutex = new Object();
	static {
		timer = new Timer();
		map = new ConcurrentHashMap<String, Object>();
	}

	/**
	 * 增加緩存對象
	 * 
	 * @param key
	 * @param ce
	 * @param validityTime
	 *            有效時間
	 */
	public static void setCache(String key, Object ce, int validityTime) {
		map.put(key, new CacheWrapper(validityTime, ce));
		timer.schedule(new TimeoutTimerTask(key), validityTime * 1000);
	}

	// 獲取緩存KEY列表
	public static Set<String> getCacheKeys() {
		return map.keySet();
	}

	public static List<String> getKeysFuzz(String patton) {
		List<String> list = new ArrayList<String>();
		for (String tmpKey : map.keySet()) {
			if (tmpKey.contains(patton)) {
				list.add(tmpKey);
			}
		}
		if (isNullOrEmpty(list)) {
			return null;
		}
		return list;
	}

	public static Integer getKeySizeFuzz(String patton) {
		Integer num = 0;
		for (String tmpKey : map.keySet()) {
			if (tmpKey.startsWith(patton)) {
				num++;
			}
		}
		return num;
	}

	/**
	 * 增加緩存對象
	 * 
	 * @param key
	 * @param ce
	 * @param validityTime
	 *            有效時間
	 */
	public static void setCache(String key, Object ce) {
		map.put(key, new CacheWrapper(ce));
	}

	/**
	 * 獲取緩存對象
	 * 
	 * @param key
	 * @return
	 */
	public static <T> T getCache(String key) {
		CacheWrapper wrapper = (CacheWrapper) map.get(key);
		if (wrapper == null) {
			return null;
		}
		return (T) wrapper.getValue();
	}

	/**
	 * 檢查是否含有制定key的緩衝
	 * 
	 * @param key
	 * @return
	 */
	public static boolean contains(String key) {
		return map.containsKey(key);
	}

	/**
	 * 刪除緩存
	 * 
	 * @param key
	 */
	public static void delCache(String key) {
		map.remove(key);
	}

	/**
	 * 刪除緩存
	 * 
	 * @param key
	 */
	public static void delCacheFuzz(String key) {
		for (String tmpKey : map.keySet()) {
			if (tmpKey.contains(key)) {
				map.remove(tmpKey);
			}
		}
	}

	/**
	 * 獲取緩存大小
	 * 
	 * @param key
	 */
	public static int getCacheSize() {
		return map.size();
	}

	/**
	 * 清除全部緩存
	 */
	public static void clearCache() {
		map.clear();
	}

	/**
	 * @projName:lottery
	 * @className:TimeoutTimerTask
	 * @description:清除超時緩存定時服務類
	 * @creater:Coody
	 * @creatTime:2014年5月7日上午9:34:39
	 * @alter:Coody
	 * @alterTime:2014年5月7日 上午9:34:39 @remark:
	 * @version
	 */
	static class TimeoutTimerTask extends TimerTask {
		private String ceKey;

		public TimeoutTimerTask(String key) {
			this.ceKey = key;
		}

		@Override
		public void run() {
			CacheWrapper cacheWrapper = (CacheWrapper) map.get(ceKey);
			if (cacheWrapper == null || cacheWrapper.getDate() == null) {
				return;
			}
			if (new Date().getTime() < cacheWrapper.getDate().getTime()) {
				return;
			}
			LocalCache.delCache(ceKey);
		}
	}

	public static boolean isNullOrEmpty(Object obj) {
		try {
			if (obj == null)
				return true;
			if (obj instanceof CharSequence) {
				return ((CharSequence) obj).length() == 0;
			}
			if (obj instanceof Collection) {
				return ((Collection<?>) obj).isEmpty();
			}
			if (obj instanceof Map) {
				return ((Map<?, ?>) obj).isEmpty();
			}
			if (obj instanceof Object[]) {
				Object[] object = (Object[]) obj;
				if (object.length == 0) {
					return true;
				}
				boolean empty = true;
				for (int i = 0; i < object.length; i++) {
					if (!isNullOrEmpty(object[i])) {
						empty = false;
						break;
					}
				}
				return empty;
			}
			return false;
		} catch (Exception e) {
			return true;
		}

	}

	private static class CacheWrapper {
		private Date date;
		private Object value;

		public CacheWrapper(int time, Object value) {
			this.date = new Date(System.currentTimeMillis() + time * 1000);
			this.value = value;
		}

		public CacheWrapper(Object value) {
			this.value = value;
		}

		public Date getDate() {
			return date;
		}

		public Object getValue() {
			return value;
		}
	}
}

 

使用方式:

//查緩存
LocalCache.getCache(key);
//清除緩存
LocalCache.removeCache(key);

 

JAVA交流羣:218481849

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章