【问题标题】:Right way to get ConfigService when bootstrap microservice引导微服务时获取 ConfigService 的正确方法
【发布时间】:2019-11-03 07:10:02
【问题描述】:

我想知道在引导我的微服务期间我是否以正确的方式获取 ConfigService。

有没有办法使用 NestFactory.createMicroservice() 来做到这一点?

async function bootstrap() {
  const app = await NestFactory.create(CoreModule, {
    logger: new MyLogger(),
  });
  const configService: ConfigService = app.get(ConfigService);
  app.connectMicroservice({
    transport: Transport.TCP,
    options: {
      port: configService.PORT,
    },
  });
  await app.startAllMicroservicesAsync();
}

【问题讨论】:

标签: node.js microservices nestjs


【解决方案1】:

是的,在 NestFactory 中有一种方法可以做到这一点,您已经以正确的方式做到了!如果你想要另一个例子,这是我的引导函数:

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: new MyLogger()
  });
  const config = app.get<ConfigService>(ConfigService);
  const port = config.get('PORT');
  configure(app, config);
  await app.listen(port);
  scribe.info(
    `Listening at http://localhost:${port}/${config.get('GLOBAL_PREFIX')}`
  );
}

MyLogger 是 Nest 默认记录器的自定义实现,configure(app, config) 是在单独的文件中完成的大量应用程序配置,以保持 bootstrap 函数精简和易于维护。当然,“收听...”也需要在投入生产之前进行更改,但是这个应用程序对我来说仍在开发中。

我唯一建议你的是改变

const configService: ConfigService = app.get(ConfigService);

const configService = app.get<ConfigService>(ConfigService);

使用app.get() 的泛型为您提供类型信息。

【讨论】:

  • 如何将createMicroservice 与configService 一起使用?
  • 我认为 OP 已经正确回答了他自己关于 Nest js 微服务的问题。谢谢你。此答案中的示例适用于常规 HTTP 服务。这也很有用。
猜你喜欢
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 2019-05-02
  • 1970-01-01
相关资源
最近更新 更多