package com.yanzuoguang.util.cache; import com.yanzuoguang.util.YzgError; import com.yanzuoguang.util.exception.CodeException; import com.yanzuoguang.util.helper.StringHelper; /** * 服务工具类 * * @author 颜佐光 */ public abstract class MemoryCacheNullUtil<T, M> { /** * 缓存的公司和数据中心Id * 缓存一个小时 */ private final MemoryCache<M> cache = new MemoryCache<>(60 * 60); /** * 缓存的公司和数据中心Id * 缓存一分钟 */ private final MemoryCache<Boolean> cacheIsNull = new MemoryCache<>(60); public MemoryCacheNullUtil() { } /** * 缓存参数 * * @param cacheSecond * @param nullSecond */ public MemoryCacheNullUtil(int cacheSecond, int nullSecond) { cache.setClearSecond(cacheSecond); cacheIsNull.setClearSecond(nullSecond); } /** * 获取数据中心Id * * @param key * @return */ public M getCheck(T key) { M databaseId = get(key); if (databaseId == null) { throw YzgError.getRuntimeException("049", key); } return databaseId; } /** * 获取数据中心Id * * @param key * @return */ public M get(T key) { String keyString = getKey(key); M value = cache.get(keyString); if (value == null) { if (StringHelper.toBoolean(cacheIsNull.get(keyString))) { return null; } value = getValue(key); setCache(keyString, value); } return value; } /** * 获取关键字 * * @param key * @return */ protected abstract String getKey(T key); /** * 获取数据 * * @param key * @return */ protected abstract M getValue(T key); /** * 写入缓存 * * @param key * @param value */ protected void setCache(String key, M value) { cacheIsNull.remove(key); cache.remove(key); if (value == null) { cacheIsNull.put(key, true); } else { cache.put(key, value); } } }