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是否存在

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章