c# - 如何在 ASP.NET Core 2.2 中使用来自不同托管项目的共享 SignalR Hub
问题描述
我正在处理一个使用 ASP.NET Core 2.2 构建的项目。主要解决方案包含多个项目,其中包括 API、Web 和其他类库。
我们使用 SignalR 来显示 API 项目和 Web 项目之间的共享消息/通知。例如,从 API 添加新员工记录应调用 SignalR Hub,并且所有 Web 客户端都应收到通知。
这是我们项目的当前结构
|- API
|- Hub_ClassLibrary
|- Services
|- Web
流动:
Web > services > Hub
API > services > Hub
中心:
public class NotificationHub : Hub
{
public async Task SendNotification(List<DocumentHistoryModel> notifications)
{
await Clients.All.SendAsync(Constants.ReceiveNotification, notifications);
}
}
网络启动类:
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notificationHub");
});
API 启动类
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notificationHub");
});
服务
private readonly IHubContext<NotificationHub> _hubContext;
public MyService(IHubContext<NotificationHub> hubContext)
{
_hubContext = hubContext;
}
await _hubContext.Clients.All.SendAsync(ReceiveNotification, notifications);
问题是,我可以从 web 发送和接收通知,但是从 api 调用,web 没有收到任何通知。我认为问题在于它为每个项目创建了两个单独的连接,但是处理这种情况的最佳方法是什么?
编辑:我可以在此 api 代码中获取连接 ID 和状态“已连接”,但是,网络仍然没有收到任何通知。也试过connection.InvokeAsync
var connection = new HubConnectionBuilder()
.WithUrl("https://localhost:44330/notificationhub")
.Build();
connection.StartAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
}
else
{
connection.SendAsync("UpdateDashboardCount", "hello world");
}
}).Wait();
解决方案
对于这种情况,您最好使用 pub/sub 系统,例如 rabbitmq、kafka、akka.net、redis。但是,如果您坚持使用 signalr,最好的解决方案是使用 signalr 创建一个消息协调器并使其成为 signalr 主机,然后您的其他服务将充当客户端,将其消息发送到该 signalr 服务并从中接收消息(您甚至可能需要实现一些逻辑来使您的按摩协调器对消息进行排队并使其持久化)此外,如果您可以迁移到 asp.net core 3,您应该明确地检查 grpc 双向流,这可能是一个完美的解决方案你的问题。
推荐阅读
- java - 使用三个堆栈的回文(Java)
- json - Terraform 语法和格式有什么区别?
- java - 在 Spock 中将 Lambda 函数定义为参数约束
- javascript - 创建 HTML 边栏时使用存储的属性
- jquery - Jquery - 模糊和keyup多次触发
- android - 如何将字符串数组返回到java JNI
- ios - 如何从 Date (2018-09-28 09:42:00 +0000 ) 中提取日期、月份和年份 (dd-MM-yyyy) 而没有日期格式的时间 - iOS swift?
- symfony - Symfony 4 - 登录后重定向用户没有活动
- python - numpy蒙面参差不齐的数组
- javascript - 组件道具在浅层渲染中未更新