NestJS NATS 请求-响应

NestJS NATS request-response

我正在尝试使用 NestJS 和 NATS 微服务。 documentation 可以很好地设置基本的请求-响应。

我所做的是:

运行 本地 NATS 服务器。

设置我的 main.ts 以连接到服务器:

async function bootstrap() {
  const app = await NestFactory.createMicroservice(AppModule, {
    options: {
      url: "nats://localhost:4222",
    },
    transport: Transport.NATS,
  });
  app.listen(() => console.log("Microservice is listening"));
}
bootstrap();

创建了一个 ClientProxyFactory 来发回消息:

export const NatsClientProvider: Provider = {
  inject: [ConfigService],
  provide: NatsClientProviderId,
  useFactory: async (config: ConfigService) =>
    ClientProxyFactory.create({
      options: {
        servers: config.getNatsConfig().servers,
      },
      transport: Transport.NATS,
    }),
};

设置控制器app.controller.ts以响应特定模式:

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    @Inject(NatsClientProviderId) private readonly natsClient: ClientProxy,
  ) {}

  @MessagePattern("hello")
  async getHello(data: string) {
    console.log("data: ", data);
    console.log("getHello!!");
    await this.natsClient.send("hello", this.appService.getHello());
    return this.appService.getHello();
  }

  async onModuleInit() {
    await this.natsClient.connect();
    console.log("Nats connected!");
  }

设置测试文件以尝试发送请求-响应消息:

import { connect } from "ts-nats";

async function start() {
  const nc = await connect({
    servers: ["nats://localhost:4222"],
  });

  const msg = await nc.request("hello", 5000, "me");
  console.log("msg: ", msg);
}

start();

当我 运行 我的 Nest 应用程序时,我可以在 NATS 服务器日志中看到正确创建的订阅。

当我 运行 test.ts 文件时,它超时 NatsError: Request timed out.。但是,我可以看到我的控制台日志(尽管数据是 undefined,即使我在发布的消息中指定了它。

returnclient.send 方法都无法从应用接收消息。

感谢任何帮助!

编辑: 仍在研究并坚持这个问题。在 Microservice docs 的 "Sending Messages" 部分,它表示 "The pattern has to be equal to this one defined in the @MessagePattern() decorator while payload is a message that we want to transmit to another microservice."。如果我这样做,Nest 应用程序会检测到它发送的消息并陷入无限循环,永远向自己发送消息和接收相同的消息。

使用 ClientProxy 时,sendemit return Observables。您需要 "activate" 那些才能让他们做任何事情。所以你可以 subscribe 给他们,或者把它改成 Promise。

因为你正在使用 await 你可能想要做

await this.natsClient.send("hello", this.appService.getHello()).toPromise();

要避免控制器中的无限循环,请删除 natsClient.send 语句。 MessagePattern 将自动发送一个回复,其中包含您 return 函数中的数据,在您的情况下 this.appService.getHello():

@MessagePattern("hello")
async getHello(data: string) {
  console.log("data: ", data);
  return "Hello World!";
}

Nest 要求您发送一个很长的 id 属性(任何字符串都可以),以便它能够回复消息。只需将其包含在数据中 json:

// Nest expects the data to have the following structure
const reply = await nc.request("hello", 500, JSON.stringify({ data: "Hello", id: "myid" }));
console.log({ reply });

在您的嵌套日志中,您会看到以下日志条目:

data: Hello

在您的测试脚本中,您会看到:

{ reply:
   { subject: '_INBOX.GJGL6RJFYXKMCF8CWXO0HB.GJGL6RJFYXKMCF8CWXO0B5',
     sid: 1,
     reply: undefined,
     size: 50,
     data: '{"err":null,"response":"Hello World!","id":"myid"}' 
} }