package com.aps.common.security.utils; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import com.alibaba.fastjson2.JSONArray; import com.aps.common.core.constant.CacheConstants; import com.aps.common.core.utils.SpringUtils; import com.aps.common.core.utils.StringUtils; import com.aps.common.redis.service.RedisService; import com.aps.system.api.domain.SysDictData; import org.springframework.util.CollectionUtils; /** * 字典工具类 * * @author ruoyi */ public class DictUtils { /** * 设置字典缓存 * * @param key 参数键 * @param dictDatas 字典数据列表 */ public static void setDictCache(String key, List dictDatas) { SpringUtils.getBean(RedisService.class).setCacheObject(getCacheKey(key), dictDatas); } /** * 获取字典缓存 * * @param key 参数键 * @return dictDatas 字典数据列表 */ public static List getDictCache(String key) { JSONArray arrayCache = SpringUtils.getBean(RedisService.class).getCacheObject(getCacheKey(key)); if (StringUtils.isNotNull(arrayCache)) { return arrayCache.toList(SysDictData.class); } return null; } /** * 删除指定字典缓存 * * @param key 字典键 */ public static void removeDictCache(String key) { SpringUtils.getBean(RedisService.class).deleteObject(getCacheKey(key)); } /** * 清空字典缓存 */ public static void clearDictCache() { Collection keys = SpringUtils.getBean(RedisService.class).keys(CacheConstants.SYS_DICT_KEY + "*"); SpringUtils.getBean(RedisService.class).deleteObject(keys); } /** * 设置cache key * * @param configKey 参数键 * @return 缓存键key */ public static String getCacheKey(String configKey) { return CacheConstants.SYS_DICT_KEY + configKey; } public static interface CacheValue{ String get(String label); } /** * 根据字典类型和字典标签获取字典值 * * @param dictType * @return */ public static CacheValue getCacheValue(String dictType) { List cacheData = StringUtils.isEmpty(dictType) ? Collections.emptyList() : getDictCache(dictType); return label -> { if (CollectionUtils.isEmpty(cacheData)){ return null; } if(StringUtils.isEmpty(label)){ return null; } return cacheData.stream().filter(item -> Objects.equals(item.getDictLabel(), label)) .findFirst() .map(SysDictData::getDictValue) .orElse(null); }; } }