package cn.lili.modules.lmk.event.eventListener;
|
|
import cn.lili.cache.Cache;
|
import cn.lili.cache.CachePrefix;
|
import cn.lili.modules.lmk.constant.RedisKeyExpireConstant;
|
import cn.lili.modules.lmk.domain.entity.Video;
|
import cn.lili.modules.lmk.event.event.VideoCommentNumCacheEvent;
|
import cn.lili.modules.lmk.service.VideoService;
|
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
|
import lombok.RequiredArgsConstructor;
|
import org.springframework.context.event.EventListener;
|
import org.springframework.stereotype.Component;
|
import org.springframework.transaction.event.TransactionPhase;
|
import org.springframework.transaction.event.TransactionalEventListener;
|
|
import java.util.Objects;
|
|
/**
|
* 事件监听器
|
*
|
* @author:xp
|
* @date:2025/6/25 14:54
|
*/
|
@Component
|
@RequiredArgsConstructor
|
public class LmkEventListener {
|
|
private final Cache cache;
|
private final VideoService videoService;
|
|
/**
|
* 新增视频评论时,更新视频评论数缓存
|
*
|
* TransactionalEventListener TransactionPhase.BEFORE_COMMIT 表示事件发起处的事务提交之前执行该事件,能保证事务
|
*
|
* @param event
|
*/
|
@TransactionalEventListener(classes = {VideoCommentNumCacheEvent.class}, phase = TransactionPhase.BEFORE_COMMIT)
|
public void videoCommentNumCache(VideoCommentNumCacheEvent event) {
|
// 初始化redis中评论的点赞数量
|
cache.put(CachePrefix.VIDEO_COMMENT_LIKE_NUM.getPrefixWithId(event.getVideoId()), 0, RedisKeyExpireConstant.COMMENT_NUM_EXPIRE, RedisKeyExpireConstant.EXPIRE_DAY);
|
// 处理视频评论数
|
Video video = videoService.getById(event.getVideoId());
|
if (cache.exist(CachePrefix.VIDEO_COMMENT_NUM.getPrefixWithId(event.getVideoId()))) {
|
cache.incr(CachePrefix.VIDEO_COMMENT_NUM.getPrefixWithId(event.getVideoId()));
|
} else {
|
if (Objects.nonNull(video)) {
|
cache.put(CachePrefix.VIDEO_COMMENT_NUM.getPrefixWithId(event.getVideoId()),
|
video.getCommentNum() + 1,
|
RedisKeyExpireConstant.COMMENT_NUM_EXPIRE,
|
RedisKeyExpireConstant.EXPIRE_DAY);
|
}
|
}
|
// 标识需要定时任务统计评论数量
|
if (Objects.nonNull(video) && ! video.getCommentNumJob()) {
|
new LambdaUpdateChainWrapper<>(videoService.getBaseMapper())
|
.eq(Video::getId, event.getVideoId())
|
.set(Video::getCommentNumJob, Boolean.TRUE)
|
.update();
|
}
|
}
|
|
}
|