我们可以使用 confirmChannel() 方法来确保消息正确发送到队列。
代码示例:
const amqp = require('amqplib');
async function sendToQueue(q, message) {
const conn = await amqp.connect('amqp://localhost');
const ch = await conn.createConfirmChannel();
await ch.assertQueue(q);
ch.sendToQueue(q, Buffer.from(message));
await ch.waitForConfirms();
await ch.close();
await conn.close();
}
sendToQueue('nonexistent_queue', 'test message')
.then(() => console.log('Message sent'))
.catch(err => console.error(err));
在上面的代码中,我们使用 createConfirmChannel() 方法创建了一个具有确认机制的通道。接下来,我们使用 assertQueue() 方法来确保队列存在。最后,我们使用 waitForConfirms() 方法用于等待消息是否成功发送到队列。如果发送失败,则会抛出错误。