【发布时间】:2021-04-29 17:31:55
【问题描述】:
我正在使用 Azure SignalR 服务进行推送通知,并且实施涉及多个集线器。在 .net 框架中,组不能跨集线器重用。使用 Azure Signal 的 .net 核心实现是否相同?
【问题讨论】:
标签: asp.net-core asp.net-core-signalr
我正在使用 Azure SignalR 服务进行推送通知,并且实施涉及多个集线器。在 .net 框架中,组不能跨集线器重用。使用 Azure Signal 的 .net 核心实现是否相同?
【问题讨论】:
标签: asp.net-core asp.net-core-signalr
ASP.NET Core SignalR 为每种集线器类型存储不同的组和连接集合。但是您可以使用 IHubContext 引用不同集线器的上下文。它将使您有可能访问其他集线器的客户端和组。实际上,这看起来不是一个好习惯......看起来它通常用于从控制器或后台工作人员而不是其他集线器发送消息。 https://docs.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0
我没有在 azure signalr 中尝试过,但尝试了我本地文档中的修改示例,它有效。这是一个如何完成此行为的示例
public class OtherHub : Hub
{
private readonly IHubContext<ChatHub> _chatHubContext;
public OtherHub(IHubContext<ChatHub> chatHubContext)
{
_chatHubContext = chatHubContext ?? throw new ArgumentNullException(nameof(chatHubContext));
}
public async Task SendMessage(string user, string message, string group)
{
await _chatHubContext.Clients.Group(group).SendAsync("RecieveMessage", user, message);
}
}
如果你对它内部如何工作感兴趣,SignalR源代码中的这个类负责管理组和连接 https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/server/Core/src/DefaultHubLifetimeManager.cs
【讨论】:
组是与名称相关联的连接集合。
https://docs.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-5.0#groups-in-signalr
我认为 - 我还没有测试过这个,所以这是非常推测的,但如果一个组只不过是一个连接的集合,你可以这样做:
// Some user defined hub
public async Task AddToGroup(string groupName)
{
// Add to own group
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
// You'd need to use the DI to inject the other hubs into this one.
MyOtherUserDefinedHub.AddToGroupAsync(Context.ConnectionId, groupName);
MySecondOtherUserDefinedHub.AddToGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
}
我认为使用示例应用程序来测试它会很容易。 这假设每个集线器都有一个连接 ID,imo 似乎很可能,但我没有在网上找到任何关于此的资源。
编辑:似乎用户 Anton 测试了连接 ID 是否在集线器之间共享 - 但显然它们不是。这意味着这个提议似乎无效并且没有内置的方法。
【讨论】: