英文:
How to publish and disconnect without having to resort to setTimeout?
问题
RabbitMQ文档中提供了一个发布消息到交换机然后在延迟500毫秒后关闭连接的示例,使用setTimeout。我决定跳过setTimeout,但如果在运行publish方法后立即关闭连接,我的消息就无法发送到RabbitMQ服务器。想象一下:
channel.publish('MyExchange', 'MyRoutingKey', Buffer.from('{}'));
await channel.close();
await connection.close();
是否有更好的方法在发送消息后关闭连接,而不是使用setTimeout?
文档链接,在“Putting it all together”部分:https://www.rabbitmq.com/tutorials/tutorial-five-javascript.html
英文:
In the documentation of RabbitMQ they give an example of publishing a message to an exchange and then closing the connection after a 500 delay using setTimeout. I decided to skip the setTimeout, but then my messages were not being sent to the RabbitMQ server if I closed the connection immediately after I ran the publish method. Imagine:
channel.publish('MyExchange', 'MyRoutingKey', Buffer.from('{}'));
await channel.close();
await connection.close();
Is there a better way to close the connection after sending a message than setting a setTimeout?
Link to documentation, at the Putting it all together section: https://www.rabbitmq.com/tutorials/tutorial-five-javascript.html
答案1
得分: 1
我应该还提供了与上述问题相关的连接和通道实例化。
解决方案是使用createConfirmChannel而不是createChannel。createConfirmChannel返回的Channel提供了waitForConfirms方法,该方法等待服务器确认所有消息已接收。
更详细的解释请参考:
- https://rabbitmq.com/publishers.html#data-safety
- https://github.com/amqp-node/amqplib/blob/main/examples/waitForConfirms.js
英文:
I should have also provided the connection and channel instantiation to the question above.
The solution was to use createConfirmChannel instead of createChannel. The Channel returned by createConfirmChannel provides a waitForConfirms method which waits to confirm that all messages were received by the server.
For a more in-depth explanation:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论