直接上代码
public class CacheCode {
private static Hashtable cachMap = new Hashtable();
//重写载入缓存信息方法
public static void putCache(String key,Object obj){
putCache(key,obj,1800);//默认半小时
}
//重写载入缓存信息方法
public static void putCache(String key,Object obj,int seconds){
Cache cache = new Cache();
cache.setKey(key);
Calendar nowTime = Calendar.getInstance();
nowTime.add(Calendar.SECOND, seconds);
cache.setTimeOut(nowTime.getTimeInMillis()/1000);
cache.setValue(obj);
cachMap.put(key,cache);
}
//获取缓存信息
public static Object getCache(String key) {
Cache cache = cachMap.get(key);
if (cache != null) { //调用判断是否终止方法
if(validate(cache)){
return cache.getValue();
}else{
cachMap.remove(key);
}
}
return null;
}
//判断缓存是否有效
private static boolean validate(Cache cache) {
return cache.getTimeOut()*1000 > Calendar.getInstance().getTimeInMillis();
}
}Cache类
public class Cache {
private String key;//缓存ID
private Object value;//缓存数据
private long timeOut;//更新时间
public Cache() {
super();
}
public Cache(String key, Object value, long timeOut) {
this.key = key;
this.value = value;
this.timeOut = timeOut;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
}