gpt4 book ai didi

java - Spring Boot WebSocket - 如何获取客户端订阅通知

转载 作者:行者123 更新时间:2023-12-01 19:43:51 28 4
gpt4 key购买 nike

我有一个包含大量组的应用程序,其中我的服务器使用消息队列 (RabbitMQ) 来观察组并在通过 WebSocket 进行更改时向用户发布通知。我正在使用 Spring boot 及其受本指南启发的 WebSocket 实现:https://spring.io/guides/gs/messaging-stomp-websocket/

以下是 JavaScript 客户端订阅 channel 的示例:

var socket = new SockJS('http://localhost/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/group/1/notification', function (message) {
// to something..
});
});

我的 Java Spring WebSocket Controller 具有此 broadcastNotification 方法,将消息发送到 /topic/group/{groupId}/notification channel 。

@Controller
public class GroupController {
private SimpMessagingTemplate template;

@Autowired
public GroupController(SimpMessagingTemplate template) {
this.template = template;
}

public void broadcastNotification(int groupId, Notification notification) {
this.template.convertAndSend("/topic/group/." + tenantId + "/notification", Notification);
}
}

工作正常,但考虑到性能,我希望我的业务逻辑仅观察当前在 WebSocket 上订阅的组。

当客户端订阅 /topic/group/1/notification/topic/group/1/* channel 时,我如何在服务器上收到通知?网络用户将在浏览网页时进行订阅和取消订阅。

最佳答案

您可以像这样监听事件SessionSubscribeEvent:

@Component
public class WebSocketEventListener {

@EventListener
public void handleSessionSubscribeEvent(SessionSubscribeEvent event) {
GenericMessage message = (GenericMessage) event.getMessage();
String simpDestination = (String) message.getHeaders().get("simpDestination");

if (simpDestination.startsWith("/topic/group/1")) {
// do stuff
}
}
}

关于java - Spring Boot WebSocket - 如何获取客户端订阅通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54330744/

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