diff --git a/boot-service/src/main/java/com/xwbing/util/CommonDataUtil.java b/boot-service/src/main/java/com/xwbing/util/CommonDataUtil.java index c953c71..8b7e483 100644 --- a/boot-service/src/main/java/com/xwbing/util/CommonDataUtil.java +++ b/boot-service/src/main/java/com/xwbing/util/CommonDataUtil.java @@ -1,7 +1,11 @@ package com.xwbing.util; +import com.alibaba.fastjson.JSONObject; + import java.util.HashMap; +import java.util.Iterator; import java.util.Map; +import java.util.Set; /** * 作者: xiangwb @@ -9,23 +13,106 @@ import java.util.Map; */ public class CommonDataUtil { private static Map token = new HashMap<>(); + private static final long EXPIRY = 1000 * 60; private CommonDataUtil() { } - public static Object getData(String key) { - return token.get(key); - } - + /** + * 存数据 + * + * @param key + * @param value + */ public static void setData(String key, Object value) { - token.put(key, value); + JSONObject object = new JSONObject(); + object.put("value", value); + object.put("expiry", -1); + token.put(key, object); } + /** + * 存数据,带有效期 + * + * @param key key + * @param value value + * @param invalid 分钟 + */ + public static void setData(String key, Object value, int invalid) { + JSONObject object = new JSONObject(); + long currentTimeMillis = System.currentTimeMillis(); + object.put("value", value); + object.put("expiry", currentTimeMillis + invalid * EXPIRY); + token.put(key, object); + } + + /** + * 获取数据 + * + * @param key + * @return + */ + public static Object getData(String key) { + JSONObject object = (JSONObject) token.get(key); + if (object != null) { + Object value = object.get("value"); + long expiry = object.getLongValue("expiry"); + if (-1 == expiry) { + return value; + } else { + long currentTimeMillis = System.currentTimeMillis(); + if (expiry >= currentTimeMillis) { + return value; + } else { + return null; + } + } + } else { + return null; + } + + } + + /** + * 删除某条数据 + * + * @param key + */ public static void removeData(String key) { token.remove(key); } - public static void clearData() { + /** + * 删除过期数据 + */ + public static void clearExpiryData() { + long currentTimeMillis = System.currentTimeMillis(); + Set> entries = token.entrySet(); + Iterator> iterator = entries.iterator(); + while (iterator.hasNext()) { + Map.Entry next = iterator.next(); + JSONObject object = (JSONObject) next.getValue(); + long expiry = object.getLongValue("expiry"); + if (-1 != expiry) { + if (expiry < currentTimeMillis) { + iterator.remove(); + } + } + } + } + + /** + * 清空所有数据 + */ + public static void clearAllData() { token.clear(); } + + public static void main(String[] args) { + CommonDataUtil.setData("a", "a", 1); + CommonDataUtil.setData("b", "b"); + Object a = CommonDataUtil.getData("a"); + Object b = CommonDataUtil.getData("b"); + CommonDataUtil.clearExpiryData(); + } }