缓存工具
package manager.common;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class LocalCacheClient {
// 缓存map
private static Map<String, Object> cacheMap = new HashMap<String, Object>();
// 缓存有效期map
private static Map<String, Long> expireTimeMap = new HashMap<String, Long>();
/**
* 获取指定的value,如果key不存在或者已过期,则返回null
* @param key
* @return
*/
public static Object get(String key) {
if (!cacheMap.containsKey(key)) {
return null;
}
if (expireTimeMap.containsKey(key)) {
if (expireTimeMap.get(key) < System.currentTimeMillis()) { // 缓存失效,已过期
return null;
}
}
return cacheMap.get(key);
}
/**
* @param key
* @param <T>
* @return
*/
public static <T> T getT(String key) {
Object obj = get(key);
return obj == null ? null : (T) obj;
}
/**
* 设置value(不过期)
* @param key
* @param value
*/
public static void set(String key, Object value) {
cacheMap.put(key, value);
}
/**
* 设置value
* @param key
* @param value
* @param millSeconds 过期时间(毫秒)
*/
public static void set(final String key, Object value, int millSeconds) {
final long expireTime = System.currentTimeMillis() + millSeconds;
cacheMap.put(key, value);
expireTimeMap.put(key, expireTime);
if (cacheMap.size() > 2) { // 清除过期数据
new Thread(new Runnable() {
public void run() {
// 此处若使用foreach进行循环遍历,删除过期数据,会抛出java.util.ConcurrentModificationException异常
Iterator<Map.Entry<String, Object>> iterator = cacheMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
if (expireTimeMap.containsKey(entry.getKey())) {
long expireTime = expireTimeMap.get(key);
if (System.currentTimeMillis() > expireTime) {
iterator.remove();
expireTimeMap.remove(entry.getKey());
}
}
}
}
}).start();
}
}
/**
* key是否存在
* @param key
* @return
*/
public static boolean isExist(String key) {
return cacheMap.containsKey(key);
}
}
缓存实现(企业微信)
package manager.common;
import com.alibaba.fastjson.JSONObject;
import manager.constant.AccessToken;
import manager.util.http.HttpUtils;
public class WXAccessToken {
public static final String corpid = "";
public static final String corpsecret = "";
// 获取access_token
public static final String gettoken_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
public static String getAccessToken(){
Object object = LocalCacheClient.get("access_token");
if (object != null) {
return object.toString();
}
String str = HttpUtils.sendGet(gettoken_url, "corpid=" + corpid + "&corpsecret=" + corpsecret);
JSONObject jsonObject = JSONObject.parseObject(str);
String errcode = jsonObject.get("errcode").toString();
if (errcode.equals("0")){
String access_token = jsonObject.get("access_token").toString();
Integer expires_in = (Integer) jsonObject.get("expires_in");
LocalCacheClient.set("access_token", access_token, expires_in * 1000);
return access_token;
}else {
return null;
}
}
}