如何发布和断开连接,而不必诉诸于 setTimeout?

huangapple go评论65阅读模式
英文:

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而不是createChannelcreateConfirmChannel返回的Channel提供了waitForConfirms方法,该方法等待服务器确认所有消息已接收。

更详细的解释请参考:

英文:

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:

huangapple
  • 本文由 发表于 2023年4月10日 20:28:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定