繁体   English   中英

将邮件从Twisted Client发布到ZeroMQ

[英]Publishing messages from Twisted Client to ZeroMQ

在我的Twisted应用程序中,我想将消息发布到ZeroMQ消息队列中。 我可以在Protocol类中做以下类似的事情吗?

from twisted.internet import protocol,reactor
import zmq

class MyClient(protocol.Protocol):
  def __init__(self):
    self.context = zmq.Context()
    self.socket =  context.socket(zmq.PUB)
    self.socket.bind("tcp://127.0.0.1:5000")

  def dataReceived(self,data):
     #Do something with the data to get a result
     #...
     #Publish to 0mq
     self.socket.send(result)

#Code below for factory and initializing reactor
#...

reactor.run()

上面的工作是否可行? 如果它不起作用,那我应该使用txZMQ( https://github.com/smira/txZMQ )吗?

谢谢

Socket.send方法的默认行为是阻塞,直到消息在套接字上排队为止。 如果套接字队列已满,则在套接字上没有空间将消息排队之前,Twisted应用程序中不会发生其他任何事情。

send方法的NOBLOCK标志告诉zmq如果无法将消息排队,则引发异常。 但是,如果执行此操作,则必须担心失败:

try:
    self.socket.send(result, flags=zmq.NOBLOCK)
except zmq.Again:
    # Failed to queue the message: what now?

使用txZMQ软件包会更简单,该软件包将ZMQ与Twisted事件循环集成在一起。 文档中示例建议您在txZMQ中实施发布,如下所示:

factory = ZmqFactory()
publisher = ZmqPubConnection(factory, endpoint)
publisher.publish(message)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM