Spring,如何使用websockets向连接的客户端广播消息?

Mic*_*ael 12 java spring stomp

我想在我的应用程序中使用websockets.我已经按照本教程:http: //spring.io/guides/gs/messaging-stomp-websocket/

它完美地运作.

当其中一个连接的客户端按下按钮时,将调用此方法:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting() throws Exception {
    System.out.println("Sending message...");
    Thread.sleep(1000); // simulated delay
    return new Greeting("hello!");        
}
Run Code Online (Sandbox Code Playgroud)

并且消息被广播给所有连接的客户端.

现在我想修改我的服务器应用程序,它将定期(每小时)向所有连接的客户端广播消息,而无需客户端的交互.

像这样的东西(但这显然不起作用):

@Scheduled(fixedRate = 3600000)
public void sendMessage(){
   try {
   @SendTo("/topic/greetings")     
   greeting();
    } catch (Exception e) {
        e.printStackTrace(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢建议.

Art*_*lan 15

@SendTo仅在从客户端收到的时候SimpAnnotationMethodMessageHandler才会启动.SubProtocolWebSocketHandlerWebSocketMessage

为了满足您的要求,您应该注入您的@Scheduled服务SimpMessagingTemplate brokerMessagingTemplate并直接使用它:

@Autowired
private SimpMessagingTemplate brokerMessagingTemplate;
.......
this.brokerMessagingTemplate.convertAndSend("/topic/greetings", "foo");
Run Code Online (Sandbox Code Playgroud)