Spring WebSocket ConvertAndSendToUser not working but convertAndSend working

拟墨画扇 提交于 2020-12-12 08:55:33

问题


I am new to Spring boot websocket and messaging semantics. Currently i am able to send private messages using the below code.

String queueName = "/user/" + username  + "/queue/wishes";
simpMessagingTemplate.convertAndSend(queueName, message);

When trying to use convertAndSendToUser I am not getting any error but the message is not getting sent. I knew that with sendToUser there should be a slight change in how the destination name should be formed but I am not getting it right.

String queueName = "/user/queue/wishes";
        simpMessagingTemplate.convertAndSendToUser(username, queueName, message);

Below is my subscription code.

 stompClient.subscribe('/user/queue/wishes', function(message) {
            alert(message);
        }) 

回答1:


I had a similar problem, if your username is actually a sessionId, then try to use one of the overloaded methods that accept headers (so said in SimpMessageSendingOperations javadoc):

SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(username);
headerAccessor.setLeaveMutable(true);

messagingTemplate.convertAndSendToUser(username, "/queue/wishes", message, headerAccessor.getMessageHeaders());

my example




回答2:


It is not getting sent because your "destination" i.e "queuename" is incorrect. As you can see here SimpMessagingTemplate.java#L230 this is the method that gets invoked as a part of the chain on invocations of template.convertAndSendToUser().

This method already prefixes /user to the final destination. So instead you should do something like this: simpMessagingTemplate.convertAndSendToUser(username,"/queue/wishes", message); Now with the correct destination it should get sent to user.




回答3:


Finally figured out the problem. I did a silly mistake. I was filling the User DestinationPrefix as part of WebSocket config. but didn't set it up for the injected bean SimpMessaging template.



来源:https://stackoverflow.com/questions/62456213/spring-websocket-convertandsendtouser-not-working-but-convertandsend-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!