寫了一個Java的簡單緩存模型

緩存操做接口java

/**
 * 緩存操做接口
 * 
 * @author xiudong
 *
 * @param <T>
 */
public interface Cache<T> {

	/**
	 * 刷新緩存數據
	 * 
	 * @param key 緩存key
	 * @param target 新數據
	 */
	void refresh(String key, T target);
	
	/**
	 * 獲取緩存
	 * 
	 * @param key 緩存key
	 * @return 緩存數據
	 */
	T getCache(String key);
	
	/**
	 * 判斷緩存是否過時
	 * 
	 * @param key 緩存key
	 * @return 若是緩存過時返回true, 不然返回false
	 */
	Boolean isExpired(String key);
	
	/**
	 * 設置緩存過時時間
	 * 
	 * @param key 緩存key
	 * @param millsec 緩存過時時間,單位:毫秒
	 */
	void setExpired(Long millsec);
	
	/**
	 * 是否存在緩存對象
	 * 
	 * @param key 緩存key
	 * @return 存在返回true,不存在返回false
	 */
	Boolean exist(String key);
}

import java.util.Date;

/**
 * 緩存實體
 * 
 * @author xiudong
 *
 * @param <T>
 */
public class LastCache<T> {
	
	/**
	 * 上次緩存的數據
	 */
	private T data;
	
	/**
	 * 最後刷新時間
	 */
	private long refreshtime;
	
	public LastCache(T data) {
		this(data, new Date().getTime());
	}
	
	public LastCache(T data, long refreshtime) {
		this.data = data;
		this.refreshtime = refreshtime;
	}
	
	public T getData() {
		return data;
	}
	
	public void setData(T data) {
		this.data = data;
	}
	
	public long getRefreshtime() {
		return refreshtime;
	}
	
	public void setRefreshtime(long refreshtime) {
		this.refreshtime = refreshtime;
	}
}

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 簡單的緩存模型
 * 
 * @author xiudong
 *
 * @param <T>
 */
public class SimpleCached<T> implements Cache<T> {

	/**
	 * 緩存數據索引
	 */
	private Map<String, LastCache<T>> cache = new ConcurrentHashMap<String, LastCache<T>>();
	
	/**
	 * 緩存超時時間,單位:毫秒
	 */
	private Long expired = 0L;
	
	public SimpleCached() {
		this(5 * 1000 * 60L);
	}
	
	public SimpleCached(Long expired) {
		this.expired = expired;
	}

	@Override
	public void refresh(String key, T target) {
		if (cache.containsKey(key)) {
			cache.remove(key);
		}
		cache.put(key, new LastCache<T>(target));
	}

	@Override
	public T getCache(String key) {
		if (!this.exist(key)) {
			return null;
		}
		
		return cache.get(key).getData();
	}

	@Override
	public Boolean isExpired(String key) {
		if (!this.exist(key)) {
			return null;
		}
		
		long currtime = new Date().getTime();
		long lasttime = cache.get(key).getRefreshtime();
		
		return (currtime - lasttime) > expired;
	}

	@Override
	public void setExpired(Long millsec) {
		this.expired = millsec;
	}

	@Override
	public Boolean exist(String key) {
		return cache.containsKey(key);
	}
	
}
相關文章
相關標籤/搜索