使用Spring 4 WebSocket从Java推送消息

我想将消息从Java推送到WebSocket客户端。 我已成功将js客户端发送到服务器并在2个js客户端上收到消息,因此客户端代码工作正常。

我的问题是,我想在Java应用程序中发生事件时发起发送。 因此,例如,每次放置10个订单时,向所有订阅的客户端发送消息。 这可能吗?

我当前的配置:

      @Controller public class MessageController { @MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting greeting() throws Exception { return new Greeting("Hello world"); } } 

我希望能做的是这样的:

 public class OrderManager { @Autowired MessageController messageController; int orderCount = 0; public void processOrder(Order o) { orderCount++; if(orderCount % 10 == 0) messageController.greeting(); } } 

所有订阅的websocket客户端都会收到一条消息。

您可以使用SimpMessagingTemplate. 它会自动注册。 只需在你想要的任何Spring bean中autowire它。

 @Autowired private SimpMessagingTemplate template; ... this.template.convertAndSend("/topic/greetings", text);