使用Spring 4 WebSocket从Java推送消息 [英] Push message from Java with Spring 4 WebSocket
问题描述
我想将消息从Java推送到WebSocket客户端。我已成功将js客户端发送到服务器并在2个js客户端上收到消息,因此客户端代码工作正常。
I'd like to push messages from Java to WebSocket clients. I've successfully made a js client send to the server and receive a message back on 2 js clients, so the client side code works fine.
我的问题是我想要在Java应用程序中发生事件时发起发送。因此,例如,每次放置10个订单时,向所有订阅的客户端发送消息。这可能吗?
My issue is that I'd like to initiate a send when events occur within the Java app. So for example every time 10 orders have been placed send a message to all subscribed clients. Is this possible?
我当前的配置:
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/hello">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
@Controller
public class MessageController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting() throws Exception {
return new Greeting("Hello world");
}
}
我希望能做的是类似这样的事情:
What I'd like to be able to do is something like this:
public class OrderManager {
@Autowired MessageController messageController;
int orderCount = 0;
public void processOrder(Order o) {
orderCount++;
if(orderCount % 10 == 0)
messageController.greeting();
}
}
并且所有订阅的websocket客户端都会收到一条消息。
and all subscribed clients to the websocket receive a message.
推荐答案
您可以使用 SimpMessagingTemplate。
它会自动注册。只需 autowire
就可以在任何你想要的Spring bean中使用它。
You can use the SimpMessagingTemplate.
It's automatically registered. Just autowire
it in any Spring bean you want.
@Autowired
private SimpMessagingTemplate template;
...
this.template.convertAndSend("/topic/greetings", text);
这篇关于使用Spring 4 WebSocket从Java推送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!