如何在多台服务器上使用SignalR?

问题描述 投票:0回答:2

我有一个用 dotnet core、singalR 和 React Native 制作的聊天应用程序。当我将其发布到单个服务器上时,我的聊天运行良好。但是当我通过 docker swarm 将其发布到多个服务器中时。我收到此错误。

无法使用任何可用的传输连接到服务器。 WebSockets 失败:错误:传输出现错误。

通过此错误消息,该应用程序有时可以正常工作。当我离开页面并返回时,它不再工作。

我使用的是ubuntu服务器。我在服务器和客户端上都对齐了 signalR 的版本。他们都使用5.0.3。我的应用程序前面没有代理服务器,我正在使用 docker swarm 的负载平衡功能。

配置服务

var tokenKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"])); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(opt => { opt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = tokenKey, ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; opt.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken)) { if (path.StartsWithSegments("/chat") || path.StartsWithSegments("/dialog")) { context.Token = accessToken; } } return Task.CompletedTask; } }; });

配置Void

app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub<ChatHub>("/chat", opt => { opt.Transports = HttpTransportType.WebSockets; }); endpoints.MapHub<DialogHub>("/dialog", opt => { opt.Transports = HttpTransportType.WebSockets; }); });


.net-core signalr docker-swarm
2个回答
2
投票

文档

中所述,Microsoft 建议引入 Redis 背板或委托给他们的托管服务 Azure SignalR。

使用 SignalR 的应用程序需要跟踪其所有连接, 这给服务器群带来了问题。添加一个服务器,就可以了 其他服务器不知道的新连接。

使用 Azure SignalR 后,
与 ASP.NET Core

应用程序集成相当简单。然后,您就可以从应用程序中卸载管理连接的所有开销。


0
投票

© www.soinside.com 2019 - 2024. All rights reserved.