Skip to main content
 首页 » 数据库

本地缓存,redis缓存综合应用

2022年07月18日27birdshome
/**
* 系统弹幕有效期(本地缓存10S,redis缓存1分钟)
**/
private static Map<String,LocalDateTime> barrageShowValidMap = new ConcurrentHashMap<>();
private static Map<String,List<BarrageShowVO>> barrageShowMap = new ConcurrentHashMap<>();
private static Long barragesShowCacheTimes = Constant.ONE_MINUTE;
private static Long barragesShowCacheLocalTimes = Constant.TEN_SECOND;

/**
* @desc : 获取系统弹幕
* @author : 毛会懂
* @create: 2021/9/18 11:01:00
**/
private List<BarrageShowVO> getSysBarrages(Integer activityId){
if (activityId == null) {
throw new BusinessException(GameErrorCodeEnum.LOTTY_PRE_VERIFY_ERROR.getErrorCode(), "活动id为空");
}

List<BarrageShowVO> barrageShowList;
// 从本地取系统弹幕
String localKey = "ACTIVITY_SYS_BARRAGE_" + activityId.toString();
LocalDateTime localDateTime = barrageShowValidMap.get(localKey);
LocalDateTime now = LocalDateTime.now();
if(localDateTime != null && localDateTime.isAfter(now)){
log.info("读本地缓存");
barrageShowList = barrageShowMap.get(localKey);
}else {
log.info("读redis缓存");
String barragesKey = RedisKeyManagement.getKey(RedisKeyManagement.ACTIVITY_SYS_BARRAGES, Arrays.asList(activityId.toString()));
barrageShowList = (List<BarrageShowVO>) redisService.get(barragesKey);
if (barrageShowList == null) {
synchronized (this) {
log.info("同步读redis缓存");
barrageShowList = (List<BarrageShowVO>) redisService.get(barragesKey);
if (barrageShowList == null) {
// 查询系统弹幕
QueryWrapper<ActivitySysBarrageDO> sysBarrageQueryWrapper = new QueryWrapper<>();
sysBarrageQueryWrapper.eq("activity_id", activityId);
sysBarrageQueryWrapper.eq("status", EnableStatusEnum.ENABLE);
List<ActivitySysBarrageDO> sysBarrageList = sysBarrageService.list(sysBarrageQueryWrapper);
barrageShowList = new ArrayList<>();
if(!CollectionUtils.isEmpty(sysBarrageList)) {
for (ActivitySysBarrageDO barrageDO : sysBarrageList) {
BarrageShowVO showVO = new BarrageShowVO();
BeanUtils.copyProperties(barrageDO,showVO);
barrageShowList.add(showVO);
}
}
redisService.set(barragesKey, barrageShowList, barragesShowCacheTimes);
}
}
}

// 添加到本地缓存
if(barrageShowList != null) {
barrageShowValidMap.put(localKey, LocalDateTime.now().plusSeconds(barragesShowCacheLocalTimes));
barrageShowMap.put(localKey, barrageShowList);
}
// 清除过期的缓存(只有map的size超过50才会清缓存,防止清缓存频率太高)
if(barrageShowValidMap.size() > 50){
Iterator<Map.Entry<String, LocalDateTime>> iterator = barrageShowValidMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, LocalDateTime> next = iterator.next();
LocalDateTime value = next.getValue();
if(value.isBefore(now)){
iterator.remove();
String key = next.getKey();
barrageShowMap.remove(key);
}
}
}
}
return barrageShowList;
}

本文参考链接:https://www.cnblogs.com/maohuidong/p/15325032.html