在 NestJS 微服务中公开普通的 http 端点 [英] Expose normal http endpoint in NestJS Microservices

查看:78
本文介绍了在 NestJS 微服务中公开普通的 http 端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 NestJs 编写了这个微服务:

I have this microservice written with 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 微服务来做到这一点

But now I need to implement an endpoint /metrics for Prometheus. So the question is how do I do this with NestJs microservice

this 问题,我觉得这是不可能的.这是真的吗?如果是这样,有没有我可以使用的解决方法?

From this issue I get the impression that it is not possible. Is this true and if so, is there a workaround I can use?

我尝试如下应用中间件

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 没有任何反应时,中间件没有被调用

But when I do curl http://localhost:5000/metrics nothing happens, the middleware is not called

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

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

更新:这个问题也无济于事:(

推荐答案

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

If you want your application to support both http requests and a microservice, you can create a 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.startAllMicroservicesAsync();
await app.listen(3001);

这篇关于在 NestJS 微服务中公开普通的 http 端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆