写了一个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);
	}
	
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值