STOMP Client的deactivate()方法是否终止WS连接?需手动取消订阅吗?
STOMP Client的
deactivate()方法与订阅取消疑问 问题描述
STOMP的Client类提供了deactivate()方法,请问该方法是否会终止所有活跃的WebSocket连接?还是需要手动取消在onConnect回调中创建的订阅?同时,以下代码中disconnect()方法里循环取消订阅的操作是否有必要?
public setWebSocketConnections(loggedUser) { let scope = this; console.info('Obtaining WS connection...'); this.stompClient = new Client({ webSocketFactory: () => new SockJS(scope.runtimeEnvironment.WEBSOCKET_ENDPOINT), connectHeaders: { 'ctx-jwt': loggedUser.temporaryToken.match(/ctx-jwt=[^;]+/)[0].split('=')[1] }, onConnect: frame => this.onConnectionSuccess(scope), reconnectDelay: 10000, heartbeatIncoming: 10000, heartbeatOutgoing: 10000 }); if (!this.runtimeEnvironment.PRODUCTION) this.stompClient.debug = console.log; this.stompClient.activate(); } private onConnectionSuccess(scope) { let liveContextFn = response => this.liveContextInProgress.next(response); // Live context modification endpoint this.subscriptions.push(scope.stompClient.subscribe('/topic/contexts/live', message => liveContextFn(JSON.parse(JSON.parse(message.body).content)))); } // Closes all active connections of the logged user public disconnect() { this.subscriptions.forEach(s => s.unsubscribe()); // Is this needed? if (this.stompClient) this.stompClient.deactivate(); }
回答
deactivate()的作用:
调用stompClient.deactivate()时,会主动关闭底层的WebSocket连接,同时STOMP客户端会自动向服务器发送UNSUBSCRIBE帧,完成所有已创建订阅的清理工作,不需要手动逐个取消。手动取消订阅的必要性:
从核心功能来说,这段循环取消订阅的代码不是必须的,因为deactivate()已经覆盖了订阅清理的逻辑。不过如果你的业务场景需要在断开连接前立刻停止接收消息(比如避免收到断开前服务器推送的最后几条消息),手动提前取消订阅可以实现这个需求,但这属于额外优化,并非强制要求。另外,如果后续还会复用这个
stompClient实例重新激活连接,那手动清理this.subscriptions列表是有必要的——避免下次连接时重复添加订阅,导致同一主题被多次订阅、重复接收消息。但如果调用deactivate()后就不再使用该实例,完全可以省略手动取消的步骤。
内容的提问来源于stack exchange,提问作者Diego Victor de Jesus
相关产品推荐
相关产品推荐

