使用Spring Boot向WebSocket客户端发送消息时,为什么必须两次指定会话ID?

时间:2019-09-04 22:32:12

标签: spring-boot websocket stomp

我正在使用Spring Boot将消息发送到特定的WebSocket用户队列。如您所见,当调用方法convertAndSendToUser时,我们将sessionId作为第一个参数,也将其传递到标头(SimpMessageHeaderAccessor)内。如果我不将sessionId放在标题中,它将不起作用。为什么会有这种冗余?这是我的代码:

@Controller
public class GreetingController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/hello")
    public void greeting(@Payload HelloMessage message, @Header("simpSessionId") String sessionId) throws Exception {
        System.out.println(message.getName() + " from " + sessionId);
        sendMessageToUser(sessionId, "/queue/greetings", new Greeting("Hello, " + message.getName()));
    }

    private void sendMessageToUser(String sessionId, String destination, Object payload) {

        // Why this? : -------------------------------------------------------------------------------------
        SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
        headerAccessor.setSessionId(sessionId);
        headerAccessor.setLeaveMutable(true);
        // -------------------------------------------------------------------------------------------------

        simpMessagingTemplate.convertAndSendToUser(sessionId, destination, payload, headerAccessor.getMessageHeaders());
    }
}

0 个答案:

没有答案