如何在Nest App中使用RabbitMQ和REST-API?

Miy*_*Ron 3 javascript rabbitmq microservices nestjs

再会!

\n

我正在尝试实施2 microservices that communicate with each other through a message broker.But one of them should accept Http requests via REST-Api。不幸的是,我不明白如何让微服务同时监听消息队列和传入的 HTTP 请求。也许我不了解通过消息代理进行通信的范式中的某些内容,但是如何接收来自客户端的请求并将其转发到微服务架构呢?

\n

主.ts

\n
import { NestFactory } from \'@nestjs/core\';\nimport { AppModule } from \'./app.module\';\nimport {Transport, MicroserviceOptions} from \'@nestjs/microservices\'\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {\n    transport: Transport.RMQ,\n    options: {\n      urls: [\'amqp://rabbitmq:5672\'],\n      queue: \'hello_world\',\n      queueOptions: {\n        durable: false\n      },\n    },\n  });\n  await app.listen();\n}\nbootstrap();\n
Run Code Online (Sandbox Code Playgroud)\n

正如您所看到的,现在应用程序没有像标准方法那样侦听端口 3000。应该做什么?

\n

Miy*_*Ron 8

答案其实很简单。NEST js 具有混合应用程序。您可以在这里了解它们https://docs.nestjs.com/faq/hybrid-application#hybrid-application。感谢大家

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {Transport, MicroserviceOptions} from '@nestjs/microservices'

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const microservice = app.connectMicroservice({
    transport: Transport.RMQ,
    options: {
      urls: ['amqp://rabbitmq:5672'],
      queue: 'hello_world',
      queueOptions: {
        durable: false
      },
    },
  });

  await app.startAllMicroservices();
  await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)