feat(count): 新增笔记评论数缓存更新逻辑

- 在 CountNoteCommentConsumer 中引入 RedisTemplate依赖
- 消费评论消息时,更新 Redis 中笔记评论总数
- 新增 RedisKeyConstants.FIELD_COMMENT_TOTAL 常量定义
- 实现基于 Hash 的评论数累加更新机制
- 优化评论数更新流程,支持批量处理与缓存同步
This commit is contained in:
2025-11-08 22:06:26 +08:00
parent 8be6719be8
commit 51cebf6215
2 changed files with 22 additions and 0 deletions

View File

@@ -31,6 +31,11 @@ public class RedisKeyConstants {
*/
private static final String COUNT_NOTE_KEY_PREFIX = "count:note:";
/**
* Hash Field: 笔记评论总数
*/
public static final String FIELD_COMMENT_TOTAL = "commentTotal";
/**
* Hash Field: 笔记收藏总数
*/

View File

@@ -5,12 +5,14 @@ import com.github.phantomthief.collection.BufferTrigger;
import com.google.common.collect.Lists;
import com.hanserwei.framework.common.utils.JsonUtils;
import com.hanserwei.hannote.count.biz.constant.MQConstants;
import com.hanserwei.hannote.count.biz.constant.RedisKeyConstants;
import com.hanserwei.hannote.count.biz.domain.mapper.NoteCountDOMapper;
import com.hanserwei.hannote.count.biz.model.dto.CountPublishCommentMqDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
@@ -27,6 +29,8 @@ public class CountNoteCommentConsumer implements RocketMQListener<String> {
@Resource
private NoteCountDOMapper noteCountDOMapper;
@Resource
private RedisTemplate<String, Object> redisTemplate;
private final BufferTrigger<String> bufferTrigger = BufferTrigger.<String>batchBlocking()
.bufferSize(50000) // 缓存队列的最大容量
@@ -67,6 +71,19 @@ public class CountNoteCommentConsumer implements RocketMQListener<String> {
// 评论数
int count = CollUtil.size(entry.getValue());
// 更新 Redis 缓存中的笔记评论总数
// 构建 Key
String noteCountHashKey = RedisKeyConstants.buildCountNoteKey(noteId);
// 判断 Hash 是否存在
boolean hasKey = redisTemplate.hasKey(noteCountHashKey);
// 若 Hash 存在
if (hasKey) {
// 累加更新
redisTemplate.opsForHash()
.increment(noteCountHashKey, RedisKeyConstants.FIELD_COMMENT_TOTAL, count);
}
// 若评论数大于零,则执行更新操作:累加评论总数
if (count > 0) {
noteCountDOMapper.insertOrUpdateCommentTotalByNoteId(count, noteId);