是否可以在 Asp.Net Core grpc 中使用不同的端口添加 grpc 服务?

Is it possible to add grpc services using different ports in Asp.Net Core grpc?

我有一个现有的 .net 核心应用程序,其中包含两个 grpc 服务(使用 grpc.core)。我有两台服务器

Server serverA = new Server(channelOptions)
            {
                Ports = { new ServerPort("0.0.0.0", 8090, credentials) },
            };
serverA.services.add(serviceA);
serverA.Start()

Server serverB = new Server(channelOptions)
            {
                Ports = { new ServerPort("0.0.0.0", 8091, credentials) },
            };
serverB.services.add(serviceB);
serverB.Start()

现在,我正在尝试从 grcp.core 迁移到 asp.net 核心 grpc,但是在添加服务时我找不到添加具有两个不同端口的两个服务的方法:

services.AddSingleton<ServiceA>();
services.AddSingleton<ServiceB>();

两者都在同一个端口,有没有办法在 asp.net 核心 grpc 中为每个服务设置一个端口?

从 3.1 模板项目ASP.NET Core gRPC Service您可以通过启动设置监听两个端口:

  "applicationUrl": "https://localhost:5001;https://localhost:5002",

并添加基于端口的分支路由,如下所示:

  app.UseRouting();
  app.MapWhen(context => context.Connection.LocalPort == 5001,
      iab => iab.UseRouting().UseEndpoints(endpoints => endpoints.MapGrpcService<GreeterService>()));
  app.MapWhen(context => context.Connection.LocalPort == 5002,
      iab => iab.UseRouting().UseEndpoints(endpoints => endpoints.MapGrpcService<GreeterServiceV2>()));