Skip to content

实时通信

youlai-aspnet 基于 SignalR 提供实时通信能力,支持消息推送、实时通知等功能。

技术架构

SignalR Hub

Hub 定义

csharp
// NotificationHub.cs
public class NotificationHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        var userId = Context.UserIdentifier;
        if (!string.IsNullOrEmpty(userId))
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, $"user_{userId}");
        }
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        var userId = Context.UserIdentifier;
        if (!string.IsNullOrEmpty(userId))
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user_{userId}");
        }
        await base.OnDisconnectedAsync(exception);
    }
}

注册 Hub

csharp
// Program.cs
builder.Services.AddSignalR()
    .AddStackExchangeRedis(builder.Configuration["Redis:ConnectionString"]);

// 映射 Hub 端点
app.MapHub<NotificationHub>("/hubs/notification");

消息推送

服务端推送

csharp
public class NotificationService
{
    private readonly IHubContext<NotificationHub> _hubContext;

    public async Task SendToUserAsync(long userId, object message)
    {
        await _hubContext.Clients.Group($"user_{userId}")
            .SendAsync("ReceiveMessage", message);
    }

    public async Task SendToAllAsync(object message)
    {
        await _hubContext.Clients.All.SendAsync("ReceiveMessage", message);
    }
}

前端接收

typescript
// Vue3 + @microsoft/signalr
import * as signalR from '@microsoft/signalr';

const connection = new signalR.HubConnectionBuilder()
  .withUrl('/hubs/notification', {
    accessTokenFactory: () => localStorage.getItem('token') || ''
  })
  .withAutomaticReconnect()
  .build();

connection.on('ReceiveMessage', (message) => {
  console.log('收到消息:', message);
});

await connection.start();

连接管理

功能实现方式
身份验证JWT Token 透传
自动重连withAutomaticReconnect()
心跳检测SignalR 内置
水平扩展Redis Backplane

应用场景

  • 系统通知推送
  • 在线用户统计
  • 实时数据更新
  • 即时消息通信

相关文件

文件说明
Youlai.Api/Hubs/NotificationHub.csSignalR Hub 定义
Youlai.Infrastructure/Services/NotificationService.cs消息推送服务
Program.csSignalR 注册配置

基于 MIT 许可发布