问题描述
我刚刚开始使用 ZMQ.我正在设计一个应用,其工作流程是:
I just got started with ZMQ. I am designing an app whose workflow is:
- 众多客户端之一(具有随机 PULL 地址)在 5555 向服务器推送请求
- 服务器永远等待客户端 PUSH.当有人来时,会为该特定请求生成一个工作进程.是的,工作进程可以同时存在.
- 当该进程完成其任务时,它会将结果推送给客户端.
我假设 PUSH/PULL 架构适合于此.请纠正我.
I assume that the PUSH/PULL architecture is suited for this. Please correct me on this.
但是我该如何处理这些场景?
But how do I handle these scenarios?
- client_receiver.recv() 将在服务器无法响应时无限等待.
- 客户端可能会发送请求,但之后会立即失败,因此工作进程将永远停留在 server_sender.send() 处.
那么如何在 PUSH/PULL 模型中设置类似超时的设置?
So how do I setup something like a timeout in the PUSH/PULL model?
编辑:感谢 user938949 的建议,我得到了一个有效的答案,我将分享给后代.
EDIT: Thanks user938949's suggestions, I got a working answer and I am sharing it for posterity.
推荐答案
如果你使用 zeromq >= 3.0,那么你可以设置 RCVTIMEO 套接字选项:
If you are using zeromq >= 3.0, then you can set the RCVTIMEO socket option:
client_receiver.RCVTIMEO = 1000 # in milliseconds
但一般来说,您可以使用轮询器:
But in general, you can use pollers:
poller = zmq.Poller()
poller.register(client_receiver, zmq.POLLIN) # POLLIN for recv, POLLOUT for send
并且 poller.poll()
需要超时:
evts = poller.poll(1000) # wait *up to* one second for a message to arrive.
evts
如果没有什么可接收的将是一个空列表.
evts
will be an empty list if there is nothing to receive.
您可以使用 zmq.POLLOUT
进行轮询,以检查发送是否成功.
You can poll with zmq.POLLOUT
, to check if a send will succeed.
或者,为了处理可能发生故障的对等点的情况,a:
Or, to handle the case of a peer that might have failed, a:
worker.send(msg, zmq.NOBLOCK)
可能就足够了,它总是会立即返回 - 如果发送无法完成,则会引发 ZMQError(zmq.EAGAIN).
might suffice, which will always return immediately - raising a ZMQError(zmq.EAGAIN) if the send could not complete.
这篇关于zeromq:如何防止无限等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!