Spring websockets - 分离MessageMapping和SendTo

时间:2016-08-04 12:10:42

标签: java spring spring-boot spring-websocket

我在第4季的websockets上遇到了以下问题,不知道为什么这个代码:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
    Thread.sleep(3000); 
    return new Greeting("Hello, " + message.getName() + "!");
}

工作正常,为什么不这样做:

@MessageMapping("/hello")
public void hehe(HelloMessage message){
    try {
        greeting(message);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
} 
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
    Thread.sleep(3000); 
    return new Greeting("Hello, " + message.getName() + "!");
}

如果服务器端的事件发生,我正在寻找解决方法如何调用greeting()方法。

1 个答案:

答案 0 :(得分:0)

将它们分开将不起作用!!

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
    Thread.sleep(3000); 
    return new Greeting("Hello, " + message.getName() + "!");
}

在服务器端事件中,如果要发送到目的地,则应使用:

simpMessagingTemplate.convertAndSend("/user/" + username + "/topic/greetings", 
       new Greeting("Hello, " + message.getName() + "!"));
// username should refer to the user in socket header if you want to send to a specific user
// omit the prefix /user/<username> if you are broadcasting

使用SIMP(您也可以使用rabbitMQ之类的消息传递方式):

@Autowired
org.springframework.messaging.simp.SimpMessagingTemplate simpMessagingTemplate;