Spring framework web sockets unique @SendTo annotation

时间:2017-10-12 09:52:13

标签: java spring

I have a web app that has registered users and i would like to push messages to users who have unique user ids. To be able to send a message to the clients, i need to know how to pass unique user id in the @sendto annotation

This is the annotation

@SendTo("/topic/uniqueuserid")
    public Greeting greeting(HelloMessage message) throws Exception {
        int uniqueuserid;
        Thread.sleep(1000); // simulated delay
        return new Greeting("Hello, " + message.getName() + uniqueuserid "!");
}

and this the stomp js

stompClient.subscribe('/topic/uniqueuserid', function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });

How can i pass a unique user id in @SendTo("/topic/uniqueuserid")

1 个答案:

答案 0 :(得分:2)

You can use @DestinationVariable annotation in a method argument, like that:

@MessageMapping("/mychat/{uniqueUserId}")
@SendTo("/topic/{uniqueUserId}")
public Message message(@DestinationVariable("uniqueUserId") Long uniqueUserId, HelloMessage message) {
    logger.info("Unique user id: {}", uniqueUserId);
}