2

我正在尝试使用 Ocelot 作为代理连接到 SignalR 集线器。SignalR 被插入到网关通过 websockets 流量的微服务中。通过 HTTP 请求的协商成功执行,但通过 websockets 的进一步通信似乎丢失了。我不知道发生了什么,尤其是当使用另一个环境中的 Azure SignalR 时,具有相同配置的通信可以完美运行。下面我介绍我的网关配置:

豹猫.json

{
  "DownstreamPathTemplate": "/{anyHub}/negotiate",
  "DownstreamScheme": "http",
  "DownstreamHostAndPorts": [
    {
      "Host": "communication",
      "Port": 80
    }
  ],
  "UpstreamHttpMethod": [ "POST" ],
  "UpstreamPathTemplate": "/{anyHub}/negotiate",
  "ReRouteIsCaseSensitive": false,
  "AuthenticationOptions": {
    "AuthenticationProviderKey": "Bearer",
    "AllowedScopes": []
  },
  "DelegatingHandlers": [
    "IdentityInQuery"
  ]
},
{
  "DownstreamPathTemplate": "/{anyHub}",
  "ReRouteIsCaseSensitive": false,
  "DownstreamScheme": "ws",
  "DownstreamHostAndPorts": [
    {
      "Host": "communication",
      "Port": 80
    }
  ],
  "UpstreamPathTemplate": "/{anyHub}",
  "UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ]
},

网关 Program.cs 的一部分

.Configure(async app =>
{
await app
    .UseCors(cors =>
{
    cors.AllowAnyHeader()
        .AllowAnyMethod()
        .SetIsOriginAllowed(x => true)
        .AllowCredentials();
}).UseOcelot();

if (turnOnWebsockets)
    app.UseWebSockets();

特定的微服务集合扩展:

public static ISignalRBuilder AddSignalRConfiguration(this IServiceCollection services, bool isDevelopment)
{
    var newServices = services.AddSignalR();
    if (!isDevelopment) newServices.AddAzureSignalR(Config.AzureSignalROptions.ConnectionString);

    return newServices;
}

public static IServiceCollection AddSignalRCors(this IServiceCollection services)
{
    services.AddCors(options => options.AddPolicy("CorsPolicy",
        builder =>
        {
            builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed(x => true)
                .AllowCredentials();
        }));

    return services;
}

IApplicationBuilder 扩展的一部分,特别是微服务:

public static IApplicationBuilder AddSignalR(this IApplicationBuilder app, bool isDevelopment)
{
    app.UseRouting()
        .UseCors("CorsPolicy");

    if (isDevelopment)
    {
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<UserHub>("/userHub");
            endpoints.MapHub<ConversationHub>("/conversationHub");
            endpoints.MapHub<DiscussionHub>("/discussionHub");
        });
    }
    ....


    return app;
}

如何将 websockets 与 Ocelot 和 SignalR 一起使用?网关目前能够与 SignalR 通信的唯一传输方法是长轮询,但对我来说并不完全令人满意。预先感谢您的任何帮助!

4

1 回答 1

3

中间件顺序很重要。

if (turnOnWebsockets)
    app.UseWebSockets();

需要在UseOcelot通话之前发生。

例子

像这样的东西应该适合你

.Configure(async app =>
{
  app.UseCors(cors =>
  {
    cors.AllowAnyHeader()
        .AllowAnyMethod()
        .SetIsOriginAllowed(x => true)
        .AllowCredentials();
  });

  if (turnOnWebsockets)
    app.UseWebSockets();

  app.UseOcelot().Wait();

笔记

到目前为止,ASP.NET Core 不支持AFAIK异步。 Configure使用.Wait()通常不受欢迎,但在这种情况下,它是必需的,也是Ocelot文档鼓励的方式。

于 2020-08-18T16:31:47.793 回答