一、功能概述

本教程将指导您在企业智能知识库项目中,完善一套完整的提交审核与审核结果消息 WebSocket 实时推送功能。

完成后,系统将具备以下能力:

  • 作者创建或编辑文档后,可以一键提交审核
  • 后端自动生成审核记录,并把文档状态切换为待审核
  • 后端通过 RabbitMQ 发布审核事件,解耦审核流程与通知流程
  • 基础服务消费审核事件后,先把通知持久化到数据库
  • 在线审核员可通过 WebSocket 实时收到“新文档待审核”消息
  • 文档作者可在审核通过或驳回后,实时收到审核结果通知
  • 点击通知后,可直接跳转到“文档审核页”
  • 离线用户重新上线后,依然可以在通知中心看到历史通知

二、技术栈

层级技术说明
前端React 18页面与交互实现
前端 UIAnt Design 5通知、表格、弹窗、布局
前端状态Zustand通知状态管理
前端通信Axios + STOMP + SockJSHTTP 接口 + WebSocket 实时推送
后端框架Spring Boot 3.2.x微服务基础框架
网关Spring Cloud Gateway统一转发 /api 与 /ws
消息队列RabbitMQ审核事件异步解耦
数据库MySQL 8审核记录、通知持久化
权限认证JWT + Spring SecurityHTTP 与 WebSocket 鉴权

三、最终效果

功能完成后,业务链路如下:

  1. 作者在创建文档页或编辑文档页点击“提交审核”
  2. kb-document 服务写入 tb_document_review
  3. 文档状态改为“待审核”
  4. kb-document 发送 SUBMITTED 审核事件到 RabbitMQ
  5. kb-foundation 监听事件,给所有审核员生成通知,并实时推送
  6. 审核员点击消息,在新窗口打开“文档审核页”
  7. 审核员在审核页点击“通过”或“驳回”
  8. kb-document 更新审核记录与文档状态,再发布 APPROVED 或 REJECTED 事件
  9. kb-foundation 给作者落库通知,并通过 WebSocket 点对点推送给作者
  10. 作者右上角通知角标和消息弹窗实时刷新

四、整体架构图

下面这张图建议在开发前先看懂整条链路。

图片.png

再看一张时序图,会更容易理解事件在不同服务之间的传递过程:

图片.png

五、数据库设计

这套功能至少依赖两张核心表:

  • tb_document_review:记录每一轮审核任务
  • kb_notification:记录审核消息,保证离线也能看见

5.1 审核记录表

参考 knowledge-base-backend/sql/02_supplement_tables.sql:

DROP TABLE IF EXISTS `tb_document_review`;
CREATE TABLE `tb_document_review` (
    `id` BIGINT(20) PRIMARY KEY COMMENT '审核记录ID(雪花ID)',
    `document_id` BIGINT(20) NOT NULL COMMENT '文档ID',
    `reviewer_id` BIGINT(20) NULL DEFAULT NULL COMMENT '审核人ID(提交审核时为NULL,审核时填入)',
    `reviewer_name` VARCHAR(50) COMMENT '审核人姓名',
    `review_result` TINYINT NULL COMMENT '审核结果:NULL-待审核,1-通过,2-驳回',
    `review_comment` TEXT COMMENT '审核意见',
    `before_status` TINYINT COMMENT '审核前状态',
    `reviewed_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '审核时间',
    `review_round` INT DEFAULT 1 COMMENT '审核轮次',
    `review_level` INT DEFAULT 1 COMMENT '审核级别(1=一级审核,预留多级扩展)',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    KEY `idx_document_id` (`document_id`),
    KEY `idx_reviewer_id` (`reviewer_id`),
    KEY `idx_reviewed_at` (`reviewed_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档审核记录表';

5.2 通知表

参考 knowledge-base-backend/sql/10_kb_foundation.sql:

DROP TABLE IF EXISTS `kb_notification`;
CREATE TABLE `kb_notification` (
  `id` BIGINT NOT NULL COMMENT '通知ID(雪花ID)',
  `user_id` BIGINT NOT NULL COMMENT '接收用户ID',
  `user_name` VARCHAR(50) DEFAULT NULL COMMENT '用户姓名(冗余字段)',
  `notification_type` VARCHAR(20) NOT NULL COMMENT '通知类型:system/comment/mention/review/like',
  `title` VARCHAR(200) NOT NULL COMMENT '通知标题',
  `content` TEXT NOT NULL COMMENT '通知内容',
  `link` VARCHAR(500) DEFAULT NULL COMMENT '跳转链接',
  `related_type` VARCHAR(50) DEFAULT NULL COMMENT '关联类型',
  `related_id` BIGINT DEFAULT NULL COMMENT '关联ID',
  `is_read` TINYINT NOT NULL DEFAULT 0 COMMENT '是否已读:0-未读,1-已读',
  `read_time` DATETIME DEFAULT NULL COMMENT '阅读时间',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `create_by` BIGINT DEFAULT NULL COMMENT '创建人ID',
  `update_by` BIGINT DEFAULT NULL COMMENT '更新人ID',
  `deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '逻辑删除标记:0-未删除,1-已删除',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_is_read` (`is_read`),
  KEY `idx_notification_type` (`notification_type`),
  KEY `idx_create_time` (`created_at`),
  KEY `idx_user_read` (`user_id`, `is_read`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统通知表';

5.3 设计要点

  • tb_document_review.reviewer_id 在“提交审核”时允许为空,因为此时还未真正处理
  • review_result 为空表示待审核,后续审核动作再更新
  • kb_notification.related_type 和 related_id 用于前端还原业务对象,本场景存 document
  • 通知一定要先入库,再做 WebSocket 推送,这样在线和离线用户都能覆盖

六、后端实现


6.1 定义审核事件 DTO

文件:knowledge-base-backend/kb-common/src/main/java/com/knowledge/base/common/event/ReviewEventDTO.java

这个 DTO 是 kb-document 和 kb-foundation 之间的通信契约。

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ReviewEventDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    /** 事件类型:SUBMITTED / APPROVED / REJECTED */
    private String eventType;

    /** 文档ID */
    private Long documentId;

    /** 文档标题 */
    private String documentTitle;

    /** 文档作者ID */
    private Long authorId;

    /** 文档作者名称 */
    private String authorName;

    /** 审核员ID */
    private Long reviewerId;

    /** 审核员名称 */
    private String reviewerName;

    /** 审核轮次 */
    private Integer reviewRound;

    /** 审核级别 */
    private Integer reviewLevel;

    /** 审核意见 */
    private String reviewComment;

    /** 事件时间 */
    private LocalDateTime timestamp;
}

为什么必须抽 DTO

  • 它能让 kb-document 只负责发事件,不依赖通知服务实现
  • 它让 kb-foundation 只关心“收到什么事件,怎么生成通知”
  • 后续如果要新增“催审”“撤回审核”等功能,直接扩展 eventType 即可

6.2 配置 RabbitMQ 审核通知队列

文件:knowledge-base-backend/kb-foundation/src/main/java/com/knowledge/base/foundation/config/RabbitMQConfig.java

关键点有三个:

  1. 定义交换机 kb.notification.exchange
  2. 定义审核通知队列 kb.notification.review.queue
  3. 使用 notification.review.* 路由键接收审核事件
public static final String NOTIFICATION_EXCHANGE = "kb.notification.exchange";
public static final String REVIEW_NOTIFICATION_QUEUE = "kb.notification.review.queue";
public static final String REVIEW_NOTIFICATION_ROUTING_KEY = "notification.review.*";

@Bean
public TopicExchange notificationExchange() {
    return new TopicExchange(NOTIFICATION_EXCHANGE, true, false);
}

@Bean
public Queue reviewNotificationQueue() {
    return QueueBuilder.durable(REVIEW_NOTIFICATION_QUEUE).build();
}

@Bean
public Binding reviewNotificationBinding() {
    return BindingBuilder.bind(reviewNotificationQueue())
            .to(notificationExchange())
            .with(REVIEW_NOTIFICATION_ROUTING_KEY);
}

消息转换器不能省

如果您要传 LocalDateTime,必须显式配置 JSON 转换器:

@Bean
public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(objectMapper);
    DefaultClassMapper classMapper = new DefaultClassMapper();
    classMapper.setTrustedPackages(
            "com.knowledge.base.common.event",
            "com.knowledge.base.foundation.dto",
            "java.util",
            "java.lang"
    );
    converter.setClassMapper(classMapper);
    return converter;
}

否则 RabbitMQ 消费端很容易因为类型映射或时间反序列化失败而报错。


6.3 配置 WebSocket STOMP 服务端

文件:knowledge-base-backend/kb-foundation/src/main/java/com/knowledge/base/foundation/websocket/WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Resource
    private WebSocketAuthInterceptor webSocketAuthInterceptor;

    @Resource
    private WebSocketHandshakeInterceptor webSocketHandshakeInterceptor;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic", "/queue");
        registry.setApplicationDestinationPrefixes("/app");
        registry.setUserDestinationPrefix("/user/");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws/notification")
                .setAllowedOriginPatterns("*")
                .setHandshakeHandler(new CustomHandshakeHandler())
                .addInterceptors(webSocketHandshakeInterceptor)
                .withSockJS();
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(webSocketAuthInterceptor);
    }
}

这里要重点理解 3 个前缀

  • /ws/notification:浏览器真正发起握手的端点
  • /topic/**:广播消息,适合所有审核员共同监听
  • /user/queue/**:点对点消息,适合推送给具体作者或具体审核员

6.4 完成 WebSocket 鉴权

这部分是很多人最容易漏掉的。

6.4.1 握手阶段鉴权

文件:knowledge-base-backend/kb-foundation/src/main/java/com/knowledge/base/foundation/websocket/WebSocketHandshakeInterceptor.java

@Override
public boolean beforeHandshake(ServerHttpRequest request,
                               ServerHttpResponse response,
                               WebSocketHandler wsHandler,
                               Map<String, Object> attributes) {
    String token = null;
    if (request.getURI().getQuery() != null) {
        String[] queryParams = request.getURI().getQuery().split("&");
        for (String param : queryParams) {
            String[] kv = param.split("=", 2);
            if ("token".equals(kv[0]) && kv.length > 1) {
                token = kv[1];
                break;
            }
        }
    }

    if (token != null && jwtUtil.validateToken(token)) {
        Long userId = jwtUtil.getUserId(token);
        if (userId != null) {
            String userIdStr = String.valueOf(userId);
            attributes.put("principal", new Principal() {
                @Override
                public String getName() {
                    return userIdStr;
                }
            });
        }
    }
    return true;
}

6.4.2 STOMP CONNECT 阶段鉴权

文件:knowledge-base-backend/kb-foundation/src/main/java/com/knowledge/base/foundation/websocket/WebSocketAuthInterceptor.java

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);

    if (StompCommand.CONNECT.equals(accessor.getCommand())) {
        String authHeader = accessor.getFirstNativeHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            if (jwtUtil.validateToken(token)) {
                Long userId = jwtUtil.getUserId(token);
                if (userId != null) {
                    accessor.setUser(() -> String.valueOf(userId));
                }
            }
        }
    }
    return message;
}

为什么握手和 CONNECT 都要做

  • 握手阶段解决 SockJS 建连时的身份绑定问题
  • CONNECT 阶段解决 STOMP 层消息会话的用户身份问题
  • 两层都做,convertAndSendToUser() 才稳定可靠

6.5 在文档服务中实现“提交审核”

文件:knowledge-base-backend/kb-document/src/main/java/com/knowledge/base/document/controller/DocumentReviewController.java

先暴露一个提交审核接口:

@PostMapping("/submit/{documentId}")
public Result<Boolean> submitForReview(@PathVariable Long documentId) {
    Boolean result = reviewService.submitForReview(documentId);
    return Result.success(result);
}

文件:knowledge-base-backend/kb-document/src/main/java/com/knowledge/base/document/service/impl/DocumentReviewServiceImpl.java

核心逻辑如下:

@Override
@Transactional(rollbackFor = Exception.class)
public Boolean submitForReview(Long documentId) {
    Document document = documentMapper.selectById(documentId);
    if (document == null) {
        throw new BusinessException("文档不存在");
    }

    if (!document.getStatus().equals(DocumentStatus.DRAFT.getCode())
            && !document.getStatus().equals(DocumentStatus.PUBLISHED.getCode())) {
        throw new BusinessException("只有草稿或已发布状态的文档才能提交审核");
    }

    Integer currentRound = jdbcTemplate.queryForObject(
            "SELECT COALESCE(MAX(review_round), 0) FROM tb_document_review WHERE document_id = ?",
            Integer.class,
            documentId
    );

    DocumentReview review = new DocumentReview();
    review.setId(SnowflakeIdGenerator.getInstance().nextId());
    review.setDocumentId(documentId);
    review.setReviewerId(null);
    review.setReviewerName(null);
    review.setReviewResult(null);
    review.setReviewComment(null);
    review.setBeforeStatus(document.getStatus());
    review.setReviewedAt(null);
    review.setReviewRound((currentRound != null ? currentRound : 0) + 1);
    review.setReviewLevel(1);
    review.setCreatedAt(LocalDateTime.now());
    documentReviewMapper.insert(review);

    document.setStatus(DocumentStatus.PENDING_REVIEW.getCode());
    documentMapper.updateById(document);

    ReviewEventDTO event = ReviewEventDTO.builder()
            .eventType("SUBMITTED")
            .documentId(documentId)
            .documentTitle(document.getTitle())
            .authorId(document.getAuthorId())
            .authorName(document.getAuthorName())
            .reviewRound(review.getReviewRound())
            .reviewLevel(review.getReviewLevel())
            .timestamp(LocalDateTime.now())
            .build();

    rabbitTemplate.convertAndSend(
            "kb.notification.exchange",
            "notification.review.submitted",
            event
    );

    return true;
}

这一段做了 4 件事

  1. 校验文档是否可提交
  2. 写入一条待审核记录
  3. 更新文档状态为待审核
  4. 发出 SUBMITTED 审核事件

6.6 实现审核通过与驳回,并发布结果事件

仍然在 DocumentReviewServiceImpl.java 中,分别实现通过与驳回。

6.6.1 审核通过

@Override
@Transactional(rollbackFor = Exception.class)
public Boolean approveReview(DocumentReviewDTO dto) {
    DocumentReview review = documentReviewMapper.selectById(dto.getReviewId());
    if (review == null) {
        throw new BusinessException("审核记录不存在");
    }
    if (review.getReviewResult() != null) {
        throw new BusinessException("该记录已审核");
    }

    Long reviewerId = UserContext.getCurrentUserId();
    String reviewerName = UserContext.getCurrentUserName();

    review.setReviewerId(reviewerId);
    review.setReviewerName(reviewerName);
    review.setReviewResult(1);
    review.setReviewComment(dto.getReviewComment());
    review.setReviewedAt(LocalDateTime.now());
    documentReviewMapper.updateById(review);

    Document document = documentMapper.selectById(review.getDocumentId());
    document.setStatus(DocumentStatus.PUBLISHED.getCode());
    document.setPublishTime(LocalDateTime.now());
    documentMapper.updateById(document);

    ReviewEventDTO event = ReviewEventDTO.builder()
            .eventType("APPROVED")
            .documentId(document.getId())
            .documentTitle(document.getTitle())
            .authorId(document.getAuthorId())
            .authorName(document.getAuthorName())
            .reviewerId(reviewerId)
            .reviewerName(reviewerName)
            .reviewRound(review.getReviewRound())
            .reviewLevel(review.getReviewLevel() != null ? review.getReviewLevel() : 1)
            .timestamp(LocalDateTime.now())
            .build();

    rabbitTemplate.convertAndSend(
            "kb.notification.exchange",
            "notification.review.approved",
            event
    );

    return true;
}

6.6.2 审核驳回

@Override
@Transactional(rollbackFor = Exception.class)
public Boolean rejectReview(DocumentReviewDTO dto) {
    if (!StringUtils.hasText(dto.getReviewComment())) {
        throw new BusinessException("驳回意见不能为空");
    }

    DocumentReview review = documentReviewMapper.selectById(dto.getReviewId());
    if (review == null) {
        throw new BusinessException("审核记录不存在");
    }
    if (review.getReviewResult() != null) {
        throw new BusinessException("该记录已审核");
    }

    Long reviewerId = UserContext.getCurrentUserId();
    String reviewerName = UserContext.getCurrentUserName();

    review.setReviewerId(reviewerId);
    review.setReviewerName(reviewerName);
    review.setReviewResult(2);
    review.setReviewComment(dto.getReviewComment());
    review.setReviewedAt(LocalDateTime.now());
    documentReviewMapper.updateById(review);

    Document document = documentMapper.selectById(review.getDocumentId());
    document.setStatus(DocumentStatus.DRAFT.getCode());
    documentMapper.updateById(document);

    ReviewEventDTO event = ReviewEventDTO.builder()
            .eventType("REJECTED")
            .documentId(document.getId())
            .documentTitle(document.getTitle())
            .authorId(document.getAuthorId())
            .authorName(document.getAuthorName())
            .reviewerId(reviewerId)
            .reviewerName(reviewerName)
            .reviewRound(review.getReviewRound())
            .reviewLevel(review.getReviewLevel() != null ? review.getReviewLevel() : 1)
            .reviewComment(dto.getReviewComment())
            .timestamp(LocalDateTime.now())
            .build();

    rabbitTemplate.convertAndSend(
            "kb.notification.exchange",
            "notification.review.rejected",
            event
    );

    return true;
}

补充说明

  • 通过后把文档状态切到 PUBLISHED
  • 驳回后把文档状态退回 DRAFT
  • 审核结果也走 RabbitMQ,而不是在 kb-document 里直接调通知接口

6.7 在基础服务中消费审核事件

文件:knowledge-base-backend/kb-foundation/src/main/java/com/knowledge/base/foundation/mq/ReviewNotificationListener.java

这是整个功能最关键的监听器。

@Slf4j
@Component
public class ReviewNotificationListener {

    @Resource
    private NotificationService notificationService;

    @Resource
    private SimpMessagingTemplate messagingTemplate;

    @Resource
    private UserAuthFeignClient userAuthFeignClient;

    @RabbitListener(queues = "kb.notification.review.queue")
    public void handleReviewEvent(ReviewEventDTO event) {
        if (event == null || event.getEventType() == null) {
            return;
        }

        String notificationType = "review";
        String link = "/review/documents/" + event.getDocumentId();

        switch (event.getEventType()) {
            case "SUBMITTED" -> handleSubmitted(event, notificationType, link);
            case "APPROVED"  -> handleApproved(event, notificationType, link);
            case "REJECTED"  -> handleRejected(event, notificationType, link);
            default -> log.warn("未知的审核事件类型:{}", event.getEventType());
        }
    }
}

6.7.1 提交审核时通知所有审核员

private void handleSubmitted(ReviewEventDTO event, String type, String link) {
    String title = "新文档待审核";
    String content = String.format(
            "用户「%s」提交了文档《%s》,请及时审核。",
            event.getAuthorName(),
            event.getDocumentTitle()
    );

    List<Long> reviewerIds = findReviewerUserIds();
    for (Long reviewerId : reviewerIds) {
        persistAndPush(reviewerId, type, title, content, link, event.getDocumentId());
    }

    Map<String, Object> payload = buildPushPayload(event, type, title, content, link);
    messagingTemplate.convertAndSend("/topic/reviewers", payload);
}

6.7.2 审核通过时通知作者

private void handleApproved(ReviewEventDTO event, String type, String link) {
    String title = "文档审核通过";
    String content = String.format("您的文档《%s》已通过审核,正式发布。", event.getDocumentTitle());

    if (event.getAuthorId() != null) {
        persistAndPush(event.getAuthorId(), type, title, content, link, event.getDocumentId());
    }
}

6.7.3 审核驳回时通知作者

private void handleRejected(ReviewEventDTO event, String type, String link) {
    String title = "文档审核驳回";
    String reason = event.getReviewComment() != null && !event.getReviewComment().isBlank()
            ? event.getReviewComment() : "未填写原因";
    String content = String.format(
            "您的文档《%s》未通过审核,驳回原因:%s",
            event.getDocumentTitle(),
            reason
    );

    if (event.getAuthorId() != null) {
        persistAndPush(event.getAuthorId(), type, title, content, link, event.getDocumentId());
    }
}

6.7.4 持久化加实时推送

private void persistAndPush(Long userId, String type, String title,
                            String content, String link, Long documentId) {
    NotificationDTO dto = new NotificationDTO();
    dto.setUserId(userId);
    dto.setNotificationType(type);
    dto.setTitle(title);
    dto.setContent(content);
    dto.setLink(link);
    dto.setRelatedType("document");
    dto.setRelatedId(documentId);
    dto.setIsRead(0);
    notificationService.sendNotification(dto);

    Map<String, Object> payload = new LinkedHashMap<>();
    payload.put("notificationType", type);
    payload.put("title", title);
    payload.put("content", content);
    payload.put("link", link);
    payload.put("documentId", documentId);

    messagingTemplate.convertAndSendToUser(
            String.valueOf(userId),
            "/queue/notifications",
            payload
    );
}

6.7.5 获取所有审核员

private List<Long> findReviewerUserIds() {
    try {
        Result<List<Long>> result = userAuthFeignClient.getUserIdsByRole("ROLE_REVIEWER");
        if (result == null || result.getData() == null) {
            return List.of();
        }
        return result.getData();
    } catch (Exception e) {
        return List.of();
    }
}

设计亮点

  • 审核员通知使用“点对点 + 广播”双保险
  • 作者通知使用点对点,避免别的用户误收
  • 即使 WebSocket 推送失败,通知仍然已经入库

6.8 通知查询接口

文件:knowledge-base-backend/kb-foundation/src/main/java/com/knowledge/base/foundation/controller/NotificationController.java

前端通知中心和角标依赖这组接口:

@GetMapping
public Result<IPage<Notification>> pageNotifications(
    @RequestParam(defaultValue = "1") Long current,
    @RequestParam(defaultValue = "10") Long size,
    @RequestParam(required = false) Integer isRead) {
    Long userId = UserContextUtil.getUserId();
    IPage<Notification> page = notificationService.pageNotifications(current, size, userId, isRead);
    return Result.success(page);
}

@PutMapping("/{id}/read")
public Result<Boolean> markAsRead(@PathVariable Long id) {
    return notificationService.markAsRead(id);
}

@PutMapping("/read-all")
public Result<Boolean> markAllAsRead() {
    Long userId = UserContextUtil.getUserId();
    return notificationService.markAllAsRead(userId);
}

@GetMapping("/unread-count")
public Result<Long> getUnreadCount() {
    Long userId = UserContextUtil.getUserId();
    return notificationService.getUnreadCount(userId);
}

如果没有这些接口,WebSocket 只能覆盖在线用户,无法保证页面刷新后的通知一致性。


七、前端实现


7.1 封装审核接口

文件:knowledge-base-frontend/src/services/review.service.ts

export const reviewService = {
  getReviewTasks: async (params?: {
    status?: string;
    page?: number;
    pageSize?: number;
    authorId?: string;
    keyword?: string;
  }) => {
    const response = await http.get<BackendPageResult>('/document/review/tasks', { params });
    return {
      list: (response as BackendPageResult).records.map(mapToReviewTask),
      total: (response as BackendPageResult).total,
    };
  },

  getCurrentReviewTask: async (documentId: string) => {
    const response = await http.get<BackendReviewRecord>(
      `/document/review/documents/${documentId}/current`
    );
    return mapToReviewTask(response as BackendReviewRecord);
  },

  reviewDocument: (taskId: string, data: { status: 'approved' | 'rejected'; comment?: string }) => {
    return http.post(`/document/review/tasks/${taskId}/review`, data);
  },

  submitForReview: (documentId: string) => {
    return http.post(`/document/review/submit/${documentId}`);
  },

  getReviewHistory: async (documentId: string) => {
    const response = await http.get<BackendReviewRecord[]>(
      `/document/review/documents/${documentId}/history`
    );
    return (response as BackendReviewRecord[]).map(mapToReviewTask);
  },
};

注意点

  • 前端统一把业务 ID 映射为字符串,避免 Long 精度丢失
  • 审核列表、审核详情页、审核历史都走这个服务层,方便维护

7.2 在创建页和编辑页调用“提交审核”

7.2.1 创建页提交审核

文件:knowledge-base-frontend/src/pages/CreateDocumentPage.tsx

const result = await createDocument(documentData);
await reviewService.submitForReview(result.id);
message.success('文档已提交审核!');
navigate('/documents');

7.2.2 编辑页重新提交审核

文件:knowledge-base-frontend/src/pages/EditDocumentPage.tsx

await documentService.updateDocument(String(documentId), documentData);
await reviewService.submitForReview(String(documentId));
message.success('文档已提交审核!');
window.open(`/documents/${documentId}`, '_blank');

设计建议

  • 创建时先保存文档,再提交审核
  • 编辑已发布文档时,也允许重新走审核流程
  • “文档创建”和“提交审核”拆成两个动作,更便于排错

7.3 封装 WebSocket 服务

文件:knowledge-base-frontend/src/services/websocket.service.ts

export interface WsNotificationPayload {
  eventType?: string;
  notificationType: string;
  title: string;
  content: string;
  link?: string;
  documentId?: EntityId;
  documentTitle?: string;
  timestamp?: string;
}

class WebSocketService {
  private client: Client | null = null;
  private notificationCallbacks: Set<NotificationCallback> = new Set();
  private reviewerCallbacks: Set<NotificationCallback> = new Set();

  onNotification(callback: NotificationCallback): () => void {
    this.notificationCallbacks.add(callback);
    return () => this.notificationCallbacks.delete(callback);
  }

  onReviewerNotification(callback: NotificationCallback): () => void {
    this.reviewerCallbacks.add(callback);
    return () => this.reviewerCallbacks.delete(callback);
  }

  connect(authToken: string, isReviewer: boolean): void {
    const socketUrl = `${WS_BASE_URL}/notification`;
    const tokenParam = authToken.replace(/^Bearer\s+/i, '');
    const sockJsUrl = `${socketUrl}?token=${encodeURIComponent(tokenParam)}`;

    this.client = new Client({
      webSocketFactory: () => new SockJS(sockJsUrl),
      connectHeaders: {
        Authorization: authToken,
      },
      heartbeatIncoming: WS_CONFIG.heartbeatInterval,
      heartbeatOutgoing: WS_CONFIG.heartbeatInterval,
      reconnectDelay: 0,
      onConnect: () => {
        this.client?.subscribe('/user/queue/notifications', (message: IMessage) => {
          const payload: WsNotificationPayload = JSON.parse(message.body);
          this.notificationCallbacks.forEach((cb) => cb(payload));
        });

        if (isReviewer) {
          this.client?.subscribe('/topic/reviewers', (message: IMessage) => {
            const payload: WsNotificationPayload = JSON.parse(message.body);
            this.reviewerCallbacks.forEach((cb) => cb(payload));
          });
        }
      },
    });

    this.client.activate();
  }
}

为什么拆成两个订阅

  • /user/queue/notifications:每个人都能收自己的审核结果
  • /topic/reviewers:只有审核员需要收“新文档待审核”的公共广播

7.4 在主布局中初始化 WebSocket

文件:knowledge-base-frontend/src/components/layout/MainLayout.tsx

这里统一管理连接生命周期最合适,因为它随着登录后的主页面长期存在。

const isReviewer = currentRoles.some((role) => {
  const upperRole = role.toUpperCase();
  return upperRole.includes('REVIEWER') || upperRole.includes('ADMIN');
});

useEffect(() => {
  if (!user?.id || !token) return;

  fetchUnreadCount().catch(() => {});

  const unsubNotification = webSocketService.onNotification(handleWsNotification);
  const unsubReviewer = webSocketService.onReviewerNotification(handleReviewerNotification);

  const authHeader = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
  webSocketService.connect(authHeader, isReviewer);

  return () => {
    unsubNotification();
    unsubReviewer();
    webSocketService.disconnect();
  };
}, [
  user?.id,
  token,
  isReviewer,
  handleWsNotification,
  handleReviewerNotification,
  fetchUnreadCount,
]);

处理个人通知

const handleWsNotification = useCallback((payload: WsNotificationPayload) => {
  const notif: SystemNotification = {
    id: `${payload.notificationType}-${payload.documentId}-${Date.now()}`,
    type: (payload.notificationType as SystemNotification['type']) || 'system',
    title: payload.title,
    content: payload.content,
    link: resolveNotificationTarget({
      type: payload.notificationType,
      link: payload.link,
      documentId: payload.documentId,
    }).url,
    documentId: payload.documentId ? String(payload.documentId) : undefined,
    read: false,
    createdAt: payload.timestamp || new Date().toISOString(),
  };
  addNotification(notif);
  showNotificationToast(notif);
}, [addNotification, showNotificationToast]);

处理审核员广播

const handleReviewerNotification = useCallback((payload: WsNotificationPayload) => {
  const notif: SystemNotification = {
    id: `review-${payload.documentId}-${Date.now()}`,
    type: 'review',
    title: payload.title,
    content: payload.content,
    link: resolveNotificationTarget({
      type: 'review',
      link: payload.link,
      documentId: payload.documentId,
    }).url,
    documentId: payload.documentId ? String(payload.documentId) : undefined,
    read: false,
    createdAt: payload.timestamp || new Date().toISOString(),
  };
  addNotification(notif);
  showNotificationToast(notif);
}, [addNotification, showNotificationToast]);

这里的关键点

  • 收到 WebSocket 消息后,不只是弹个 toast,而是同步写入 Store
  • 这样右上角角标、通知中心列表、弹窗提示三者才会保持一致

7.5 通知状态管理

文件:knowledge-base-frontend/src/stores/notification.store.ts

核心能力有 3 个:

  • 首次加载历史通知
  • WebSocket 新消息插入列表头部
  • 递增未读数
addNotification: (notification: SystemNotification) => {
  set((state) => ({
    notifications: [notification, ...state.notifications],
    unreadCount: notification.read
      ? Number(state.unreadCount)
      : Number(state.unreadCount) + 1,
  }));
},

incrementUnreadCount: (delta: number = 1) => {
  set((state) => ({
    unreadCount: Math.max(0, Number(state.unreadCount) + delta),
  }));
},

通知原始字段映射也很重要:

function mapNotification(raw: any): SystemNotification {
  const documentId = String(raw?.relatedId ?? extractDocumentIdFromLink(raw?.link) ?? '');
  const target = resolveNotificationTarget({
    type: raw?.notificationType,
    link: raw?.link,
    documentId,
  });
  return {
    id: String(raw?.id ?? ''),
    type: (raw?.notificationType as SystemNotification['type']) || 'system',
    title: (raw?.title as string) || '',
    content: (raw?.content as string) || '',
    link: target.url,
    documentId: documentId || undefined,
    read: Boolean(raw?.isRead ?? raw?.read ?? false),
    createdAt: (raw?.createdAt as string) || '',
  };
}

7.6 统一通知跳转逻辑

文件:knowledge-base-frontend/src/utils/notification-link.ts

export const buildReviewPageLink = (documentId: string | number) =>
  `/review/documents/${documentId}`;

export const isReviewPageLink = (link?: string) =>
  Boolean(link && /^\/review\/documents\/[^/]+/.test(link));

export const resolveNotificationTarget = (notification: {
  type?: string;
  link?: string;
  documentId?: string | number;
}): NotificationTarget => {
  if (isReviewPageLink(notification.link)) {
    return {
      url: notification.link,
      openInNewTab: true,
    };
  }

  const reviewDocumentId = notification.documentId ?? (
    notification.type === 'review' ? extractDocumentIdFromLink(notification.link) : undefined
  );

  if (reviewDocumentId) {
    return {
      url: buildReviewPageLink(reviewDocumentId),
      openInNewTab: true,
    };
  }

  return {
    url: notification.link,
    openInNewTab: false,
  };
};

为什么要抽工具函数

  • 通知中心、右上角弹窗、后续站内消息列表都能复用
  • 一处修改跳转策略,所有入口同步生效

7.7 增加文档审核页

路由文件:knowledge-base-frontend/src/router/index.tsx

{
  path: '/review/documents/:documentId',
  element: (
    <ProtectedRoute requireAdmin>
      <Suspense fallback={<LoadingFallback />}>
        <DocumentReviewWorkspacePage />
      </Suspense>
    </ProtectedRoute>
  ),
},

页面文件:knowledge-base-frontend/src/pages/DocumentReviewWorkspacePage.tsx

这个页面负责承接审核通知跳转,读取文档详情、当前审核任务和审核历史。

加载当前审核任务和历史

const loadData = useCallback(async () => {
  if (!documentId) return;
  setLoading(true);
  try {
    const [docRes, currentRes, historyRes] = await Promise.all([
      documentService.getDocument(documentId),
      reviewService.getCurrentReviewTask(documentId),
      reviewService.getReviewHistory(documentId),
    ]);
    setDocument(docRes);
    setCurrentTask(currentRes);
    setHistory(historyRes || []);
  } finally {
    setLoading(false);
  }
}, [documentId]);

提交审核动作

const submitReview = async (status: 'approved' | 'rejected', comment?: string) => {
  if (!pendingTask) {
    message.warning('当前文档没有待处理的审核任务');
    return;
  }
  setSubmitting(true);
  try {
    await reviewService.reviewDocument(pendingTask.id, { status, comment });
    message.success(status === 'approved' ? '审核已通过' : '已驳回该文档');
    setRejectOpen(false);
    setRejectComment('');
    await loadData();
  } finally {
    setSubmitting(false);
  }
};

这个页面解决了两个问题

  • 审核员不必从审核列表里来回切换,可直接通过消息进入
  • 审核动作闭环完成后,作者可以立即收到审核结果通知

八、配置文件


8.1 后端基础服务配置

文件:knowledge-base-backend/kb-foundation/src/main/resources/application.yml

关键配置如下:

spring:
  rabbitmq:
    host: 117.72.88.11
    port: 5672
    username: admin
    password: susan123
    virtual-host: /

websocket:
  enabled: true
  path: /ws/notification
  allowed-origins: "*"

你本地开发时至少要确认

  • RabbitMQ 可以连接
  • JWT 密钥和登录服务一致
  • 网关已放通 /ws/**

8.2 前端 WebSocket 配置

文件:knowledge-base-frontend/src/config/index.ts

export const WS_BASE_URL = import.meta.env.VITE_WS_BASE_URL || '/ws';

export const WS_CONFIG = {
  enabled: import.meta.env.VITE_WS_ENABLED === 'true',
  reconnectInterval: parseInt(import.meta.env.VITE_WS_RECONNECT_INTERVAL || '5000'),
  maxReconnectTimes: parseInt(import.meta.env.VITE_WS_MAX_RECONNECT || '5'),
  heartbeatInterval: parseInt(import.meta.env.VITE_WS_HEARTBEAT || '30000'),
} as const;

文件:knowledge-base-frontend/.env.development

VITE_API_BASE_URL=/api
VITE_WS_BASE_URL=/ws
VITE_WS_ENABLED=true
VITE_WS_RECONNECT_INTERVAL=5000
VITE_WS_HEARTBEAT=30000

为什么 VITE_WS_BASE_URL 用 /ws

因为前端开发环境通常通过 Vite 代理转发到网关,这样前端不需要写死具体域名,开发和部署都更灵活。

十、测试

按顺序启动下面这些微服务:

kb-auth-user

kb-foundation

kb-document

kb-gateway

启动前端

cd knowledge-base-frontend

npm run dev

浏览器访问我的文档页面:

http://localhost:3002/my-documents

图片.png

修改一个已发布的文档:

图片.png

然后去审核列表审核通过该文档:

图片.png

在页面右上角会有websocket消息实时推送,几秒之后会自动消失。

图片.png

点击消息推送窗口中的查看详情,可以跳转到审核详情页面:

图片.png

总结

这套“提交审核 + 审核结果消息 WebSocket 实时推送”功能,本质上由四部分组成:

  • 审核业务:负责写审核记录、改文档状态
  • 事件总线:RabbitMQ 负责解耦文档服务和通知服务
  • 通知中心:负责消息落库、未读数和历史消息查询
  • 实时通道:WebSocket 负责把在线消息实时推到前端
最后修改:2026 年 10 月 24 日
如果觉得我的文章对你有用,请随意赞赏