未收到回复队列中使用amqplib发送到RabbitMQ并由NestJS处理的消息

r8uurelv  于 2023-03-08  发布在  RabbitMQ
关注(0)|答案(1)|浏览(220)

因此,我使用带有RabbitMQ传输(Transport.RMQ)的NestJS(v8)来监听消息
我的NestJS代码看起来像这样:

// main.ts

const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
  transport: Transport.RMQ,
  options: {
    urls: ['amqp://localhost:5672'],
    queue: 'my-queue',
    replyQueue: 'my-reply-queue'
  },
});
// my.controller.ts

import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';

@Controller()
export class MyController {
  @MessagePattern('something')
  do(data: {source: string}): {source: string} {
    console.log(data);

    data.source += ' | MyController';

    return data;
  }
}

在Node.JS应用程序中,我使用amqplib发送到NestJS应用程序并接收响应
下面是Node.JS应用程序的代码:

const queueName = 'my-queue';
const replyQueueName = 'my-reply-queue';

const amqplib = require('amqplib');

async function run() {
  const conn = await amqplib.connect('amqp://localhost:5672');
  const channel = await conn.createChannel();

  await channel.assertQueue(queueName);
  await channel.assertQueue(replyQueueName);

  // Consumer: Listen to messages from the reply queue
  await channel.consume(replyQueueName, (msg) => console.log(msg.content.toString()));

  // Publisher: Send message to the queue
  channel.sendToQueue(
    queueName,
    Buffer.from(
      JSON.stringify({
        pattern: 'something',
        data: { source: 'node-application' },
      })
    ),
    { replyTo: replyQueueName }
  ); 
}

run()

当我运行节点和Nest.JS应用程序时,Nest.JS从Node.JS发布者那里获得消息,但是Node.JS消费者从来没有被调用过回复

m1m5dgzv

m1m5dgzv1#

修复方法是在Node.JS应用程序发送的数据中添加id键:

// ...

// Publisher: Send message to the queue
channel.sendToQueue(
  queueName,
  Buffer.from(
    JSON.stringify({
      // Add the `id` key here so the Node.js consumer will get the message in the reply queue
      id: '',
      
      pattern: 'something',
      data: { source: 'node-application' },
    })
  ),
  { replyTo: replyQueueName }
); 

// ...

详细说明(Nest.JS源代码中)

这是因为在server-rmq.ts文件的handleMessage函数中,检查消息的id属性是否为undefined

// https://github.com/nestjs/nest/blob/026c1bd61c561a3ad24da425d6bca27d47567bfd/packages/microservices/server/server-rmq.ts#L139-L141

 public async handleMessage(
    message: Record<string, any>,
    channel: any,
  ): Promise<void> {
    // ...

    if (isUndefined((packet as IncomingRequest).id)) {
      return this.handleEvent(pattern, packet, rmqContext);
    }

    // ...
  }

并且在handleEvent函数中没有将消息发送到应答队列的逻辑,只是处理事件

相关问题