12月 2023

关于spring框架使用websocket + stomp协议时的发消息顺序问题

还是继续上一篇stomp的问题,这次是在实际使用中又有了新发现,那就是java后端向前端发送stomp消息时,存在底层异步操作造成的消息顺序不确定性问题,如下:

    @Autowired
    SimpMessageSendingOperations messagingTemplate;

    @MessageMapping("/create")
    @SendToUser("/queue/reply")
    public ReplyDTO create(@Payload CreateDTO msg, SimpMessageHeaderAccessor accessor) throws Exception {
        String userId = getUserId(accessor);
        if (userId.isEmpty())
            return buildNotLoggedInReply(accessor);
        int createId = myService.create(userId, msg.getTypeName());
        CreateInfo ci = myService.info(createId);
        String infoStr = new ObjectMapper().writeValueAsString(ci);

        messagingTemplate.convertAndSendToUser(
                Objects.requireNonNull(accessor.getSessionId()),
                "/queue/response",
                buildOkResp(accessor),
                createHeaders(accessor.getSessionId())
        );

        return buildReply(accessor, infoStr);
    }
Continue reading…