PublicAffairs/gather-app/src/main/java/com/ruoyi/cache/DictCache.java

92 lines
3.2 KiB
Java
Raw Normal View History

package com.ruoyi.cache;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ruoyi.database.domain.SysDictDataMp;
import com.ruoyi.database.service.SysDictDataMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 字典缓存
*
* @author 戴鹏涛
* @since 2023-09-13 15:40:44
*/
@Component
public class DictCache {
/**
* key: dictType-dictValuevalue: dictLabel; place_category-1居民小区
* key: dictType-dictLabelvalue: dictValue; place_category-居民小区1
*/
private static final Cache<String, String> cache = Caffeine.newBuilder().build();
private static SysDictDataMpService sysDictDataMpService;
@Autowired
DictCache(SysDictDataMpService sysDictDataMpService) {
DictCache.sysDictDataMpService = sysDictDataMpService;
//初始化
DictLabelLoad();
DictValueLoad();
}
public static String getDictLabel(String key) {
return cache.get(key, s -> {
try {
List<String> split = StrUtil.split(key, "-");
String dictType = split.get(0);
String dictValue = split.get(1);
return sysDictDataMpService.getOne(new LambdaQueryWrapper<SysDictDataMp>()
.eq(SysDictDataMp::getDictType, dictType)
.eq(SysDictDataMp::getDictValue, dictValue)).getDictLabel();
} catch (Exception e) {
return "";
}
});
}
public static String getDictValue(String key) {
return cache.get(key, s -> {
try {
List<String> split = StrUtil.split(key, "-");
String dictType = split.get(0);
String dictLabel = split.get(1);
return sysDictDataMpService.getOne(new LambdaQueryWrapper<SysDictDataMp>()
.eq(SysDictDataMp::getDictType, dictType)
.eq(SysDictDataMp::getDictLabel, dictLabel)).getDictValue();
} catch (Exception e) {
return "";
}
});
}
/**
* 缓存刷新
*/
@Scheduled(cron = "0 0 3 * * ?")
public static void refresh() {
DictLabelLoad();
DictValueLoad();
}
private static void DictLabelLoad() {
List<SysDictDataMp> list = sysDictDataMpService.list();
Map<String, String> dictMap = list.stream().collect(Collectors.toMap(e -> StrUtil.format("{}-{}", e.getDictType(), e.getDictValue()), SysDictDataMp::getDictLabel, (v1, v2) -> v2));
cache.putAll(dictMap);
}
private static void DictValueLoad() {
List<SysDictDataMp> list = sysDictDataMpService.list();
Map<String, String> dictMap = list.stream().collect(Collectors.toMap(e -> StrUtil.format("{}-{}", e.getDictType(), e.getDictLabel()), SysDictDataMp::getDictValue, (v1, v2) -> v2));
cache.putAll(dictMap);
}
}