2026-06-30 24681c81c09022f584a57006f2534b5f74723414
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package cn.iocoder.yudao.module.im.service.websocket;
 
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.module.im.service.websocket.notification.ImNotificationWebSocketDTO;
import cn.iocoder.yudao.module.infra.api.websocket.WebSocketSenderApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.validation.annotation.Validated;
 
import java.util.Collection;
import java.util.Set;
 
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertLinkedSet;
 
/**
 * IM WebSocket 推送 Service 实现类
 * <p>
 * 当调用方处于事务中时,推送会延迟到事务提交后再异步执行,
 * 避免客户端收到 WebSocket 消息时数据库变更尚未可见。
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class ImWebSocketServiceImpl implements ImWebSocketService {
 
    @Resource
    private WebSocketSenderApi webSocketSenderApi;
 
    @Override
    public void sendNotificationAsync(Collection<Long> userIds, Integer conversationType, Integer contentType,
                                      Object payload) {
        ImNotificationWebSocketDTO notification = buildNotification(conversationType, contentType, payload);
        executeAfterTransaction(() -> getSelf().doSendNotification(userIds, notification));
    }
 
    @Override
    public void broadcastNotificationAsync(Integer conversationType, Integer contentType, Object payload) {
        ImNotificationWebSocketDTO notification = buildNotification(conversationType, contentType, payload);
        executeAfterTransaction(() -> getSelf().doBroadcastNotification(notification));
    }
 
    private static ImNotificationWebSocketDTO buildNotification(Integer conversationType, Integer contentType,
                                                                Object payload) {
        return new ImNotificationWebSocketDTO()
                .setConversationType(conversationType)
                .setContentType(contentType)
                .setPayload(payload);
    }
 
    /**
     * 异步发送 WebSocket 通知
     */
    @Async
    public void doSendNotification(Collection<Long> userIds, ImNotificationWebSocketDTO notification) {
        for (Long userId : getDistinctUserIds(userIds)) {
            try {
                webSocketSenderApi.sendObject(UserTypeEnum.ADMIN.getValue(), userId,
                        ImNotificationWebSocketDTO.TYPE, notification);
            } catch (Exception e) {
                log.error("[doSendNotification][userId({}) notification({}) 发送失败]", userId, notification, e);
            }
        }
    }
 
    /**
     * 异步广播 WebSocket 通知
     */
    @Async
    public void doBroadcastNotification(ImNotificationWebSocketDTO notification) {
        try {
            webSocketSenderApi.sendObject(UserTypeEnum.ADMIN.getValue(),
                    ImNotificationWebSocketDTO.TYPE, notification);
        } catch (Exception e) {
            log.error("[doBroadcastNotification][notification({}) 广播失败]", notification, e);
        }
    }
 
    private static Set<Long> getDistinctUserIds(Collection<Long> userIds) {
        return convertLinkedSet(userIds, userId -> userId);
    }
 
    /**
     * 事务感知的任务调度
     *
     * @param task 待执行的推送任务
     */
    private void executeAfterTransaction(Runnable task) {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            task.run();
            return;
        }
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
 
            @Override
            public void afterCommit() {
                task.run();
            }
 
        });
    }
 
    /**
     * 获得自身的代理对象,解决 @Async AOP 代理问题
     */
    private ImWebSocketServiceImpl getSelf() {
        return SpringUtil.getBean(getClass());
    }
 
}