xiangpei
9 天以前 1cdb060a8aa59b0979f7609db1781805528e76e7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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();
        }
    }
 
}