gaoluyang
6 天以前 c55aca77e84607238c3354168a8642176c575ca1
yudao-module-system/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImpl.java
@@ -2,7 +2,9 @@
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.module.infra.api.websocket.WebSocketSenderApi;
import cn.iocoder.yudao.module.system.dal.dataobject.notify.NotifyTemplateDO;
import cn.iocoder.yudao.module.system.service.notify.dto.NotifyMessagePushDTO;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -31,6 +33,9 @@
    @Resource
    private NotifyMessageService notifyMessageService;
    @Resource
    private WebSocketSenderApi webSocketSenderApi;
    @Override
    public Long sendSingleNotifyToAdmin(Long userId, String templateCode, Map<String, Object> templateParams) {
        return sendSingleNotify(userId, UserTypeEnum.ADMIN.getValue(), templateCode, templateParams);
@@ -54,7 +59,32 @@
        // 发送站内信
        String content = notifyTemplateService.formatNotifyTemplateContent(template.getContent(), templateParams);
        return notifyMessageService.createNotifyMessage(userId, userType, template, content, templateParams);
        Long messageId = notifyMessageService.createNotifyMessage(userId, userType, template, content, templateParams);
        // 实时推送:前端铃铛收到后立即刷新未读数,避免只能等待轮询
        pushToWebSocket(userId, userType, messageId, template, content);
        return messageId;
    }
    /**
     * 通过 WebSocket 把站内信实时推送给用户(该用户所有在线页面都会收到)
     *
     * 说明:推送只是“提前通知前端刷新”,推送失败不影响站内信本身,因此这里吞掉异常仅记录日志。
     */
    private void pushToWebSocket(Long userId, Integer userType, Long messageId,
                                 NotifyTemplateDO template, String content) {
        if (messageId == null) {
            return;
        }
        NotifyMessagePushDTO message = new NotifyMessagePushDTO();
        message.setMessageId(messageId);
        message.setTemplateCode(template.getCode());
        message.setTemplateNickname(template.getNickname());
        message.setTemplateContent(content);
        try {
            webSocketSenderApi.sendObject(userType, userId, NotifyMessagePushDTO.MESSAGE_TYPE, message);
        } catch (Exception ex) {
            log.warn("[pushToWebSocket][向用户({}/{})推送站内信({})失败]", userId, userType, messageId, ex);
        }
    }
    @VisibleForTesting