【问题标题】:How to run and connect two nestjs grpc microservices on the same machine如何在同一台机器上运行和连接两个nestjs grpc微服务
【发布时间】:2019-09-09 07:23:26
【问题描述】:

我正在使用 nestjs 创建 Grpc 微服务。如何连接本地主机上的两台服务器。

我尝试使用 ngrok 为其中一项服务创建隧道,但我仍然收到错误 “正在使用的地址”“在已解决的总共 2 个地址中没有添加地址” 即使两者都在不同的端口上运行

第一次服务

import { authServiceOptions } from './auth/grpc/auth.options';
import { notificationClientServiceOptions } from '../../notification/src/notification/grpc/notification.options';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.setGlobalPrefix('api/v1/services');

  // Services
  app.connectMicroservice(notificationClientServiceOptions);
  app.connectMicroservice(authServiceOptions);

  await app.startAllMicroservicesAsync();
  await app.listen(51700);
}
bootstrap();

二次服务

import { AppModule } from './app.module';
import { notificationServiceOptions } from './notification/grpc/notification.options';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.setGlobalPrefix('api/v1/services');

  // Services
  app.connectMicroservice(notificationServiceOptions);

  await app.startAllMicroservicesAsync();
  await app.listen(3001);
}
bootstrap();

// 第二个服务的客户端选项

export const notificationClientServiceOptions: ClientOptions = {
  transport: Transport.GRPC,
  options: {
    url: 'https://b6a4cd09.ngrok.io/',
    package: 'notification',
    protoPath: join(__dirname, './notification.proto'),
  },
};

【问题讨论】:

    标签: microservices grpc nestjs


    【解决方案1】:

    想通了!原来我为 Grpc 服务指定了一个 http url。这是第二个服务的正确客户端选项。

    export const notificationClientServiceOptions: ClientOptions = {
      transport: Transport.GRPC,
      options: {
        // you can specify any port that is not in use (just don't prefix it with 'http')
        url: 'localhost:5500', 
        package: 'notification',
        protoPath: join(__dirname, './notification.proto'),
      },
    };
    

    我还查阅了 nestjs 的源代码。结果表明,任何微服务的默认 url 都是 localhost:5000 因此,如果您正在运行多个服务,最好为每个服务指定 url。

    我遇到的另一个问题是连接微服务; 如果服务位于两个单独的nestjs 项目中,则不需要在firstService 中使用app.connectMicroservice(secondServiceOptions),这是因为await app.startAllMicroservicesAsync() 会尝试启动这两个服务但它会失败。这是因为secondService 已经在一个单独的项目中运行。

    要从firstService 连接到secondService,请使用@Client(secondServiceOptions) 装饰器。

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 2022-11-25
      • 2020-05-29
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 2012-10-26
      • 2020-02-02
      • 1970-01-01
      相关资源
      最近更新 更多