.NET Core 3.1 SignalR搭配Ionic5+Angular8 重启Hub后消息逐次重复问题
SignalR连接重启后消息重复问题排查与修复
核心根因
你观察到的“每重启一次连接,收到的消息数就多一条”的现象,根本不是后端Hub的问题,完全是客户端两个细节处理不到位导致的:
- 页面每次进入的时候,都会给SignalRService里的
message$流新增一个订阅,但是页面离开的时候根本没把这个订阅取消掉,这些残留的订阅会一直留在内存里。 - SignalRService是根注入的全局单例,
message$这个Subject也是常驻的——只要有订阅者绑在它上面,后续每次推消息,所有绑在上面的订阅回调都会被触发一次。你每进出一次页面就多绑一个订阅,第一次进页面1个订阅收1条消息,第二次进2个订阅收2条,和你遇到的现象完全对上。 - 还有个小问题:关Hub连接的时候,没把之前绑在连接上的
on事件监听解绑,跑久了也会攒内存泄漏。
分步修复方案
1. 组件端增加订阅取消逻辑
在页面组件中存储每次订阅返回的Subscription实例,在页面离开时主动取消订阅,避免旧的订阅残留:
import { Subscription } from 'rxjs'; export class MyPage { // 存储当前页面对message$的订阅实例 private messageSubscription: Subscription; constructor(private signalRService: SignalRService) { } ionViewDidEnter() { this.initSignalRConnection(); } initSignalRConnection(){ this.signalRService.init('1234', 'myHub', 'token'); // 保存订阅返回的实例,用于后续取消 this.messageSubscription = this.signalRService.message$.subscribe((message: NewMessage) => { console.log('got message'); this.handleMessage(message); }); } ionViewWillLeave(){ // 离开页面时先取消订阅,再关闭Hub连接 if (this.messageSubscription) { this.messageSubscription.unsubscribe(); } this.signalRService.closeConnection(); } handleMessage(message: NewMessage) { // 原有消息处理逻辑 } }
2. 优化SignalRService的连接关闭逻辑
为SignalRService新增字段记录当前连接对应的Group标识,关闭连接时先解绑Hub上绑定的事件监听,再停止连接:
@Injectable({ providedIn: 'root' }) export class SignalRService { private hubConnection: signalR.HubConnection // 新增字段记录当前连接的Group标识 private currentGroupId: string; public message$: Subject<NewMessage> = new Subject<NewMessage>(); constructor() { } public init(id: string, hub: string, token: string) { if (!this.hubConnection) { this.currentGroupId = `group${id}`; console.log('init signalR'); this.hubConnection = new signalR.HubConnectionBuilder() .withUrl(`http://ipaddress/${hub}?groupId=${this.currentGroupId}`, { accessTokenFactory: () => token }) .build(); this.hubConnection.start().then(() => { console.log('hub connection started'); }).catch(err => { console.log(err); }); this.hubConnection.on(this.currentGroupId, (message: NewMessage) => { console.log('signalR pass message'); this.message$.next(message); }); } } public closeConnection() { if (this.hubConnection) { console.log('close connection'); // 先解绑Hub上的Group事件监听 this.hubConnection.off(this.currentGroupId); this.hubConnection.stop(); this.hubConnection = null; } } }
补充注意事项
你当前使用的
@aspnet/signalr@1.1.4是微软已停止维护的旧版本,后续维护时可切换到官方长期支持的@microsoft/signalr包,选择和后端.NET Core 3.1匹配的3.1.x版本,避免出现连接层面的兼容问题。
内容的提问来源于stack exchange,提问作者user3132295
相关产品推荐
相关产品推荐

