public class LocalCache { private static ConcurrentHashMap<String, LocalCacheItem> map = new ConcurrentHashMap<String, LocalCacheItem>(); public static boolean containsKey(String key){ return map.containsKey(key); } public static void put(String key, Object value){ put(key, value, 0);//0值代表永不过期 } public static void put(String key, Object value, long expireTimeMillis){ LocalCacheItem item = new LocalCacheItem(value, System.currentTimeMillis(), expireTimeMillis); map.put(key, item); } public static Object get(String key) { return key == null ? null : getValue(key); } private static Object getValue(String key) { LocalCacheItem item = map.get(key); if (item == null) return null; long currentTime = System.currentTimeMillis(); if (item.getExpireTimeMillis() > 0 && item.getExpireTimeMillis() < currentTime - item.getCreateTimeMillis()) { map.remove(key); return null; } return item.getValue(); } static class LocalCacheItem { /** * 缓存对象 */ private Object value; /** * 缓存创建时间 */ private long createTimeMillis; /** * 缓存过期时间,0值代表永不过期 */ private long expireTimeMillis; public LocalCacheItem(Object value, long createTimeMillis, long expireTimeMillis) { this.value = value; this.createTimeMillis = createTimeMillis; this.expireTimeMillis = expireTimeMillis; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public long getCreateTimeMillis() { return createTimeMillis; } public void setCreateTimeMillis(long createTimeMillis) { this.createTimeMillis = createTimeMillis; } public long getExpireTimeMillis() { return expireTimeMillis; } public void setExpireTimeMillis(long expireTimeMillis) { this.expireTimeMillis = expireTimeMillis; } } }
@Override public WechatConfigInfo getWechatConfigInfoByAppCode(Integer appCode) { String localCacheKey = WechatConstant.LOCAL_CACHE_WECHAT_CONFIG + appCode; WechatConfigInfo cfg = (WechatConfigInfo)LocalCache.get(localCacheKey); if (cfg != null)) { return cfg; } if (checkValid) { cfg = wechatConfigInfoMapper.getWechatConfigInfoByAppCode(appCode); LocalCache.put(localCacheKey, cfg, defaultExpireTimeMinutes*60*1000); return cfg; } cfg = wechatConfigInfoMapper.getWechatConfigInfoByAppCode(appCode); LocalCache.put(localCacheKey, cfg, defaultExpireTimeMinutes*60*1000); return cfg; }
原文:https://www.cnblogs.com/zfzf1/p/10931257.html