【问题标题】:Expose normal http endpoint in NestJS Microservices在 NestJS 微服务中公开普通的 http 端点
【发布时间】:2020-01-14 11:22:30
【问题描述】:

我有这个用 NestJs 编写的微服务:

async function bootstrap() {
  const port = parseInt(process.env.PORT || '5000', 10);

  const app = await NestFactory.createMicroservice(ApplicationModule, {
    transport: Transport.TCP,
    options: { host: '0.0.0.0', port }
  });
  app.listen(() => console.log(`Microservice is listening on port ${port}`));
}
bootstrap();

但现在我需要为 Prometheus 实现一个端点 /metrics。所以问题是我如何使用 NestJs 微服务来做到这一点

this issue 我得到的印象是这是不可能的。这是真的吗?如果是的话,有没有我可以使用的解决方法?

我尝试如下应用中间件

Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService, DBService],
})
export class ApplicationModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(MetricsMiddleware)
      .forRoutes('/metrics') // Also tried '*'
  }
}

但是当我做curl http://localhost:5000/metrics 没有任何反应时,中间件没有被调用

@Injectable()
export class MetricsMiddleware implements NestMiddleware {
    constructor() {}

    use(req, res, next) {
        console.log('yes');
        next();
    }
}

更新:This issue 也无济于事:(

【问题讨论】:

    标签: javascript node.js typescript microservices nestjs


    【解决方案1】:

    如果您希望您的应用程序同时支持 http 请求和微服务,您可以创建一个hybrid application

    // Create your regular nest application.
    const app = await NestFactory.create(ApplicationModule);
    
    // Then combine it with your microservice
    const microservice = app.connectMicroservice({
      transport: Transport.TCP,
      options: { host: '0.0.0.0', port: 5000 }
    });
    
    await app.startAllMicroservices();
    await app.listen(3001);
    

    【讨论】:

    • 如果我希望我的所有微服务都能够支持 http 请求,而且能够相互通信怎么办。这可能吗?
    • @Shirohige 看看这个帖子:stackoverflow.com/a/53996635/4694994
    • 等等,这已经是一个混合应用程序了……你什么意思?它们都可以通过“微服务协议”或http相互通信。
    • 所以我试图从多个微服务向我的 Web 应用程序公开端点。例如,如果我在 /users 上执行 GET 请求,它将到达来自用户服务的端点,如果我在 /notifications 上执行 GET 请求,它将到达来自 Notifications 服务的端点。对于混合应用程序,在我看来,只有连接所有微服务的“主”应用程序能够公开端点并连接到其他微服务,或者所有其他微服务也应该使用混合方法进行实例化?
    • startAllMicroservicesAsync() 现在已弃用。您可以类似地使用替代方法:await app.startAllMicroservices();
    猜你喜欢
    • 2019-05-28
    • 2011-03-03
    • 2021-06-25
    • 2020-07-09
    • 2011-09-11
    • 1970-01-01
    • 2021-01-12
    • 2021-04-23
    • 2019-08-19
    相关资源
    最近更新 更多