我正在使用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());
}
}