0

我正在通过 RabbitMQ 处理 nodejs 请求。我的生产者通过 nodejs 路由接收请求并将它们发送给消费者,然后消费者通过从请求中接收到的数据在数据库中创建一个文档。这是我的路线

router.post("/create-user", async(req: Request, res: Response) => {
  const msg = JSON.stringify(req.body);
  const send = await Producer(msg);
});

这是我的制片人课程

import amqp from "amqplib/callback_api";

export async function Producer(message: string) {
  amqp.connect("amqp://localhost", (error0, connection) => {
    if (error0) {
      throw error0;
    }
    connection.createChannel((error1, channel) => {
      if (error1) {
        throw error1;
      }

      let queue = "hello";

      channel.assertQueue(queue, {
        durable: false,
      });
      channel.sendToQueue(queue, Buffer.from(message));
      console.log(" [x] Sent %s", message);
    });
  });
}

还有我的消费者

import amqp from "amqplib/callback_api";
import {
  User
} from "../models/user";

export class ConsumerClass {
  public async ConsumerConnection() {
    amqp.connect("amqp://localhost", (error0, connection) => {
      if (error0) {
        throw error0;
      } else {
        this.ConsumerTask(connection);
      }
    });
  }

  public async ConsumerTask(connection: amqp.Connection) {
    connection.createChannel((error1, channel) => {
      if (error1) {
        throw error1;
      }

      let queue = "hello";

      channel.assertQueue(queue, {
        durable: false,
      });

      channel.prefetch(1);

      console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queue);

      channel.consume(queue, async(msg) => {
        console.log(" [x] Received %s", msg.content.toString());
        const data = JSON.parse(msg.content.toString());
        const user = new User({
          name: data.name,
          phone: data.phone,
          company: data.company,
        });
        await user.save();
      }, {
        noAck: true,
      });
    });
  }
}

我想将从消费者创建的用户的 Json 文档发送到路由,以便客户端可以获得创建的用户作为响应。我怎样才能做到这一点,我做错了什么?

4

1 回答 1

0

您想要的是从消费者到生产者的响应事件。现在,您可以在这里创建一个充当远程过程调用的函数。

因此,将有 2 个事件 e1 和 e2,而不是两个事件。这是一个解释这些东西的小图(免责声明 - 我不擅长绘图)。我想你可以管理这个的编码部分。

在此处输入图像描述

于 2020-02-21T09:59:06.963 回答