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