Azure Web PubSub监听程序随机断开问题排查求助
排查Node.js Azure Web PubSub监听程序随机断开且重连失效的问题
问题场景
运行在AWS EC2实例Docker容器中的Node.js PubSub监听程序,基于Azure Web PubSub SDK开发,运行数天后会随机断开连接;CPU、内存无异常峰值,容器保持运行,但PubSub连接已关闭;配置了重连逻辑,但仅能看到连接关闭日志,重连未触发。
现有重连代码片段
function connect(ws: WebSocket) { ws.on('error', (error) => console.log(error)); ws.on('open', () => console.log( '******** Pubsub listening to messages! ********* ', new Date().toISOString() ) ); ws.on('close', (e) => { console.log( 'Service connection is CLOSED. Reconnect will be attempted in 5s.', e ); setTimeout(function () { connect(ws); }, 5000); }); ws.on('message', async (data) => { console.log('Message received: %s %s', data, new Date().toISOString()); .. .. .. .. }); }
核心问题分析
重连逻辑失效的直接原因:在close事件回调中,你尝试复用已关闭的WebSocket实例调用connect函数,但WebSocket连接关闭后,该实例无法再次用于建立新连接,必须创建全新的WebSocket实例才能发起重连。
排查与修复建议
1. 修复重连逻辑,创建新WebSocket实例
重构代码,每次重连时生成新的WebSocket连接实例,替换原有复用旧实例的逻辑:
// 重构为创建新连接的逻辑 function createAndConnect() { // 此处需替换为实际的Azure Web PubSub连接URL生成逻辑(含有效Token) const ws = new WebSocket('your-azure-pubsub-connection-url'); ws.on('error', (error) => console.error('[WebSocket错误]', new Date().toISOString(), error.stack || error)); ws.on('open', () => console.log( '******** Pubsub listening to messages! ********* ', new Date().toISOString() ) ); ws.on('close', (e) => { console.log( 'Service connection is CLOSED. Reconnect will be attempted in 5s.', `关闭代码: ${e.code}, 原因: ${e.reason}` ); setTimeout(createAndConnect, 5000); }); ws.on('message', async (data) => { console.log('Message received: %s %s', data, new Date().toISOString()); // 原有消息处理逻辑 }); } // 初始启动连接 createAndConnect();
2. 增强错误日志与状态监控
- 扩展
error事件日志,记录错误栈、错误代码等详细信息,便于定位断开根源:ws.on('error', (error) => { console.error('[WebSocket错误]', new Date().toISOString(), error.stack || error); }); - 在
close事件中记录关闭代码(e.code)和原因(e.reason),Azure Web PubSub会通过这些字段传递断开原因(如超时、服务端维护、Token过期等)。
3. 排查网络层面的断开诱因
- 检查AWS实例/容器的网络超时配置:确认安全组、负载均衡是否存在TCP空闲超时规则,若连接长时间无数据传输,可能被中间网络设备主动断开。可通过Azure Web PubSub SDK配置
keepAlive心跳机制,维持连接活跃。 - 验证Docker容器网络模式:排查桥接模式下的端口映射、网络隔离是否导致连接异常。
4. 检查Azure Web PubSub服务端配置
- 登录Azure Portal查看Web PubSub服务日志,确认是否为服务端主动断开连接,以及具体原因(如订阅过期、权限变更、服务维护)。
- 确认客户端连接Token的有效期,若Token过期会导致连接断开,重连时需重新生成有效Token。
5. 优化重连策略
增加指数退避重连机制,避免短时间内频繁重连给服务端带来压力,同时提升重连成功率:
let reconnectDelay = 5000; const maxDelay = 60000; function createAndConnect() { const ws = new WebSocket('your-azure-pubsub-connection-url'); ws.on('open', () => { console.log('******** Pubsub listening to messages! ********* ', new Date().toISOString()); // 重连成功后重置延迟 reconnectDelay = 5000; }); ws.on('close', (e) => { console.log(`Service connection is CLOSED. Reconnect will be attempted in ${reconnectDelay}ms.`, `关闭代码: ${e.code}, 原因: ${e.reason}`); setTimeout(() => { createAndConnect(); // 指数退避:延迟翻倍,不超过最大值 reconnectDelay = Math.min(reconnectDelay * 2, maxDelay); }, reconnectDelay); }); // 其他事件监听... }
内容的提问来源于stack exchange,提问作者fullstack_realm
相关产品推荐
相关产品推荐

