gpt4 book ai didi

java - Spring websockets - 分离 MessageMapping 和 SendTo

转载 作者:行者123 更新时间:2023-11-30 07:13:45 24 4
gpt4 key购买 nike

我在 spring 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() 方法。

最佳答案

将它们分开是行不通的!!

@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;

关于java - Spring websockets - 分离 MessageMapping 和 SendTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38766965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com