验证中...
支持针对每个key设置过期时间的本地缓存工具
原始数据 复制代码
import java.util.concurrent.ConcurrentHashMap;
/**
* <p>
* Description: 简易版本地缓存工具。可为每个key设置过期时间。
* </p>
*
* @author chenjianwen
* @version 1.0
* @Date 2018-06-12
*/
public class LocalCacheUtil {
private static ConcurrentHashMap<String, CacheData> cache = new ConcurrentHashMap<>();
public static <T> T get(String key, Class<T> clazz) {
CacheData<T> data = cache.get(key);
long now = System.currentTimeMillis();
if (data != null && now <= data.getExpireTime()) {
return data.getData();
}
cache.remove(key);
return null;
}
/**
* <p>
* Description:
* </p>
*
* @param expire 过期时间(毫秒)
* @return
* @author chenjianwen
* @date 2018/06/12
*/
public static <T> void put(String key,T data,long expire){
long now = System.currentTimeMillis();
CacheData<T> cacheData = new CacheData<>(data, now + expire);
cache.put(key,cacheData);
}
public static class CacheData<T> {
private T data;
private Long expireTime; // 过期时间戳
public CacheData(T data, Long expireTime) {
this.data = data;
this.expireTime = expireTime;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Long getExpireTime() {
return expireTime;
}
}
}

评论列表( 0 )

你可以在登录后,发表评论

11_float_left_people 11_float_left_close