问题
For example in publishing any messages we are using setTimeout()
I tried to remove the timeout, but it doesn't publish any message.
setTimeout(function () {
var t = pub.send(mes + ' ' + stringObject, 0);
}, 1000);
I am using NodeJS ZMQ npm module.
Is there any other approach to PUB
/SUB
pattern without adding setTimeout()
function?
Thanks
回答1:
I highly recommend you read the guide, it answers this question along with many others.
The reason you need to add the setTimeout()
is because the PUB
socket will send the message when it is ready, it will not wait until your subscribers are ready. So, what's going on when you omit the timeout is something like the following:
SETUP PUB SETUP SUB
| |
BIND |
| CONNECT
| |
FINISH BINDING |
| |
| |
SEND MSG1--[| |
| |
|]--------------FINISH CONNECTING
| |
SEND MSG2---- |
| | |
| ---- |
| | |
| ----[RECV MSG2]
| |
... ...
... your publisher can bind()
immediately, it doesn't need to go make a request from any network resource. Your subscriber must go out and establish its connection to the publisher, which takes time. So, the publisher is ready, and sends MSG1
to... nowhere, because no subscribers are ready for it. It's dropped, silently. After the subscriber finishes connecting, it can then receive MSG2
without issue.
The reason for this is because PUB/SUB is designed to be used when information goes stale quickly - like a newspaper. If you're producing a newspaper, and on day one you don't have any subscribers, you're not going to be holding the same edition of your newspaper for the next day when you actually get some subscribers - you'd be sending them old news. You scrap it and write another edition for your new subscribers.
If this doesn't fit your data model, then perhaps a different socket pairing would work better for you. Any other socket type will wait until it has a peer to send its message.
来源:https://stackoverflow.com/questions/32472549/zeromq-how-to-get-rid-of-settimeout-in-zeromq-zmq-implementation-of-publishing