Value对象缓存用Hash防穿透

@Override
public Long lastMomentId(Long lessonId, Long userId) {
    Long challengeMomentId = 0L;
    String key = RedisKeyUtil.build(RedisConstants.ChallengeMoment.LAST_MOMENT_ID, lessonId, userId);

    if(hashRedisTemplate.exists(key)) {
        String json = hashRedisTemplate.hget(key, RedisConstants.HashEntity.VALUE);
        if(StringUtils.isNotBlank(json)) {
        challengeMomentId = Long.parseLong(json);
    }
    }else {
        ChallengeMoment challengeMoment = challengeMomentRepository.findFirstByMap(Mapper.sql("lesson.last.moment"), new MapBuilder()
        .append("createBy", userId)
        .append("lessonId", lessonId)
        .build());
        if(null != challengeMoment) {
            challengeMomentId = challengeMoment.getId();
            hashRedisTemplate.hset(key, RedisConstants.HashEntity.VALUE, String.valueOf(challengeMomentId));
            hashRedisTemplate.hset(key, RedisConstants.HashEntity.FLAG, RedisConstants.HashEntity.FLAG_EXIST); //防穿透
        }else {
            hashRedisTemplate.hset(key, RedisConstants.HashEntity.FLAG, RedisConstants.HashEntity.FLAG_NOT_EXIST);
        }
        hashRedisTemplate.expire(key, CommonConstants.Time.THREE_DAY);
    }
    return challengeMomentId;
}

@Override
public void addLastMomentId(Long lessonId, Long userId, Long momentId) {
    String key = RedisKeyUtil.build(RedisConstants.ChallengeMoment.LAST_MOMENT_ID, lessonId, userId);
    hashRedisTemplate.hset(key, RedisConstants.HashEntity.FLAG, RedisConstants.HashEntity.FLAG_EXIST);
    hashRedisTemplate.hset(key, RedisConstants.HashEntity.VALUE, String.valueOf(momentId));
    hashRedisTemplate.expire(key, CommonConstants.Time.THREE_DAY);
}

备注: hash中的flag字段来保持key一直存在..使用exist key判断是否需要查库.. 然后用flag的值来判断value是否存在..或者直接判断value是否存在

评论

暂无评论