package com.iailab.framework.dict.core; import cn.hutool.core.util.ObjectUtil; import com.iailab.framework.common.core.KeyValue; import com.iailab.framework.common.util.cache.CacheUtils; import com.iailab.module.system.api.dict.DictDataApi; import com.iailab.module.system.api.dict.dto.DictDataRespDTO; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.time.Duration; import java.util.List; /** * 字典工具类 * * @author iailab */ @Slf4j public class DictFrameworkUtils { private static DictDataApi dictDataApi; private static final DictDataRespDTO DICT_DATA_NULL = new DictDataRespDTO(); // TODO @puhui999:GET_DICT_DATA_CACHE、GET_DICT_DATA_LIST_CACHE、PARSE_DICT_DATA_CACHE 这 3 个缓存是有点重叠,可以思考下,有没可能减少 1 个。微信讨论好私聊,再具体改哈 /** * 针对 {@link #getDictDataLabel(String, String)} 的缓存 */ private static final LoadingCache, DictDataRespDTO> GET_DICT_DATA_CACHE = CacheUtils.buildAsyncReloadingCache( Duration.ofMinutes(1L), // 过期时间 1 分钟 new CacheLoader, DictDataRespDTO>() { @Override public DictDataRespDTO load(KeyValue key) { return ObjectUtil.defaultIfNull(dictDataApi.getDictData(key.getKey(), key.getValue()).getCheckedData(), DICT_DATA_NULL); } }); /** * 针对 {@link #getDictDataLabelList(String)} 的缓存 */ private static final LoadingCache> GET_DICT_DATA_LIST_CACHE = CacheUtils.buildAsyncReloadingCache( Duration.ofMinutes(1L), // 过期时间 1 分钟 new CacheLoader>() { @Override public List load(String dictType) { return dictDataApi.getDictDataLabelList(dictType); } }); /** * 针对 {@link #parseDictDataValue(String, String)} 的缓存 */ private static final LoadingCache, DictDataRespDTO> PARSE_DICT_DATA_CACHE = CacheUtils.buildAsyncReloadingCache( Duration.ofMinutes(1L), // 过期时间 1 分钟 new CacheLoader, DictDataRespDTO>() { @Override public DictDataRespDTO load(KeyValue key) { return ObjectUtil.defaultIfNull(dictDataApi.parseDictData(key.getKey(), key.getValue()).getCheckedData(), DICT_DATA_NULL); } }); public static void init(DictDataApi dictDataApi) { DictFrameworkUtils.dictDataApi = dictDataApi; log.info("[init][初始化 DictFrameworkUtils 成功]"); } @SneakyThrows public static String getDictDataLabel(String dictType, Integer value) { return GET_DICT_DATA_CACHE.get(new KeyValue<>(dictType, String.valueOf(value))).getLabel(); } @SneakyThrows public static String getDictDataLabel(String dictType, String value) { return GET_DICT_DATA_CACHE.get(new KeyValue<>(dictType, value)).getLabel(); } @SneakyThrows public static List getDictDataLabelList(String dictType) { return GET_DICT_DATA_LIST_CACHE.get(dictType); } @SneakyThrows public static String parseDictDataValue(String dictType, String label) { return PARSE_DICT_DATA_CACHE.get(new KeyValue<>(dictType, label)).getValue(); } }