我正在通过 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 文档发送到路由,以便客户端可以获得创建的用户作为响应。我怎样才能做到这一点,我做错了什么?