1.场景:库表里存储了大量的银行支行基础数据,需要根据前端传来的总行id查到关联的全部支行数据,并全部返回前端,页面做成支行下拉场景。
2.问题:普通的接口调用逻辑,由于数据达到万条以上会有响应很慢,数据过多,前端报错等等.
3.解决:使用scheduleWithFixedDelay缓存方式
①创建缓存类处理
package com.*.misc.service.helper;
import com.*.misc.service.entity.DataEasBankEntity;
import com.*.misc.service.mapper.DataEasBankMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @author sync
*/
@Slf4j
public class BankInfoCache {
private final ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<>();
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);
private DataEasBankMapper dataEasBankMapper;
/**
* @param initialDelay 执行第一次任务延迟多长时间
* @param period 任务执行时间间隔
* @param unit 单位
* @param mapper mapper
*/
public BankInfoCache(int initialDelay, int period, TimeUnit unit, DataEasBankMapper mapper) {
// 在这里执行更新缓存的操作
scheduler.scheduleWithFixedDelay(this::updateCache, initialDelay, period, unit);
dataEasBankMapper = mapper;
}
public Object get(String key) {
return cache.get(key);
}
public void put(String key, Object value) {
cache.put(key, value);
}
public void updateCache() {
log.info("开始更新");
if (dataEasBankMapper != null) {
List<String> newKeys = Lists.newArrayList();
//查询支行全部数据
List<DataEasBankEntity> list = dataEasBankMapper.selectList(null);
log.info("获取到的数据 {}", list);
//以总行id作为key存入缓存中
Map<String, List<DataEasBankEntity>> map = ListUtils.emptyIfNull(list).stream().filter(e -> !StringUtils.isBlank(e.getBankid()))
.collect(Collectors.groupingBy(DataEasBankEntity::getBankid));
if (!map.isEmpty()) {
map.forEach((key, value) -> {
cache.remove(key);
cache.put(key, value);
newKeys.add(key);
});
}
cache.forEach((key, value) -> {
if (!newKeys.contains(key)) {
cache.remove(key);
}
});
}
}
public void remove(String key) {
cache.remove(key);
}
public void shutdown() {
scheduler.shutdown();
}
}
②初始化:
这里定义程序运行后的5秒向缓存中初始化数据,后面每小时更新缓存一次。
/**
* 向缓存中初始化数据
*/
@PostConstruct
public void init() {
log.info("初始化方法");
bankInfoCache = new BankInfoCache(5, 3600, TimeUnit.SECONDS, dataEasBankMapper);
}
③使用:
直接根据前端传来的easBankId作为key去获取缓存中数据
@Override
public List<EasBankNameDropDownVO> easSysBranchBankDropDown(EasBankNameDropDownDTO dto) {
Object bankInfoCacheData = bankInfoCache.get(dto.getEasBankId());
log.info("缓存中获取数据:{}", JSON.toJSONString(bankInfoCacheData));
List<EasBankNameDropDownVO> list = JSON.parseArray(JSON.toJSONString(bankInfoCacheData), EasBankNameDropDownVO.class);
return list;
}