Div*_*Div 5 c# signalr asp.net-core asp.net-core-2.2
我正在处理一个使用 ASP.NET Core 2.2 构建的项目。主解决方案包含多个项目,其中包括API、Web等类库。
我们已经使用 SignalR 来显示 API 项目和 Web 项目之间的共享消息/通知。例如,从 API 添加新员工记录应调用 SignalR Hub,所有 Web 客户端都应收到通知。
这是我们项目的当前结构
|- API
|- Hub_ClassLibrary
|- Services
|- Web
Run Code Online (Sandbox Code Playgroud)
流动:
Web > services > Hub
API > services > Hub
Run Code Online (Sandbox Code Playgroud)
中心:
public class NotificationHub : Hub
{
public async Task SendNotification(List<DocumentHistoryModel> notifications)
{
await Clients.All.SendAsync(Constants.ReceiveNotification, notifications);
}
}
Run Code Online (Sandbox Code Playgroud)
Web启动类:
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notificationHub");
});
Run Code Online (Sandbox Code Playgroud)
API启动类
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notificationHub");
});
Run Code Online (Sandbox Code Playgroud)
服务
private readonly IHubContext<NotificationHub> _hubContext;
public MyService(IHubContext<NotificationHub> hubContext)
{
_hubContext = hubContext;
}
await _hubContext.Clients.All.SendAsync(ReceiveNotification, notifications);
Run Code Online (Sandbox Code Playgroud)
问题是,我可以从 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();
Run Code Online (Sandbox Code Playgroud)
对于这种情况,您最好使用发布/订阅系统,例如rabbitmq、kafka、akka.net、redis。但是,如果您坚持使用信号器,最好的解决方案是使用信号器创建一个消息协调器,并将其设为信号器主机,然后您的其他服务将充当客户端,将消息发送到该信号器服务并从中接收消息(您甚至可能需要实现一些逻辑来让你的按摩协调器对消息进行排队并使它们持久化)此外,如果你可以迁移到asp.net core 3,你绝对应该检查grpc双向流,这可以是一个完美的解决方案你的问题。
| 归档时间: |
|
| 查看次数: |
1496 次 |
| 最近记录: |