java - Spring websockets - 分离 MessageMapping 和 SendTo

标签 java spring spring-boot spring-websocket

我在 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/

相关文章:

spring - Spring命令行JSON配置包含数组

即使我设置了条件,Spring Cache也不会忽略Null键

java - 使用@SpringBootTest时如何在测试类中 Autowiring bean

mysql - 使用kafka插入表后读取数据

java - 从 API 模型设计 DTO

java - 在Java中设置窗口形状(异型JFrame)

java - 使用 Maven 构建 Spring 和 Spring Security 3.1

Spring MVC 映射@RequestBody 与包含点的变量

java - 我如何知道 JFrame 何时处于最大化状态 Java Swing

java - 身份验证 Oauth 2.0 谷歌日历