在 ZeroMQ 中调用 recv_pyobj() 时如何添加主题过滤器?

How to add topic filters when calling recv_pyobj() in ZeroMQ?

ZeroMQ 提供了关于如何设置 pub-sub pattern with the topic filter, as described in the api docs. ZeroMQ also provides the methods socket.send_json() and socket.send_pyobj() (and the recv counterparts) for convenience 的非常好的文档。

在 pub-sub 示例中,主题过滤器(一个字符串)附加到消息(也是一个字符串)的开头。使用内置序列化时,有什么方法可以设置主题过滤器吗?如果我使用 send_pyobj() 发送 dictClass,我不能在它前面附加一个字符串。

首先要注意的是 ZeroMQ 不提供 send_json()send_pyobj() 作为便利方法,这些是由 pyzmq 绑定提供的。因此,ZMQ 对这些数据类型一无所知——基本上发生的事情是这些方法只是在后台执行数据的序列化和反序列化。

像你一样,我还没有看到 pub/sub 使用这些不只是订阅 '' 的便捷方法的一个例子。但是,它 应该 是可能的,如果这样做有点麻烦的话。

您可以 see here in the sourcesend_pyobj() 使用 pickle 序列化数据。您可以使用该事实来查看您的数据在序列化后的样子。您可以向 dictClass 添加一个额外的元素,前提是您可以确定它在序列化字符串中先 ,然后查看序列化和只需使用字符串的开头作为您的订阅主题。如果您不能确定您的主题元素会排在第一位,那么您将不得不创建一个您可以更好地控制的某种信封,然后将其与您的里面的数据,当你收到它时就取消引用它。

Hacky,丑陋,最终可能是个坏主意,even according to the writers of the pyzmq binding themselves - 相关引用(强调):

we do provide three builtin serialization methods for convenience, to help Python developers learn libzmq... These methods designed for convenience, not for performance, so developers who do want to emphasize performance should use their own serialized send/recv methods.

最好自己序列化数据并在第一帧中发送包含您的主题的正确多帧消息。你可以找到这样的例子 here.

// publisher
self.socket.send_multipart([b'status',pickle.dumps(msg2)])

// subscriber
socket.setsockopt(zmq.SUBSCRIBE, 'status')
[topic,msg] = socket.recv_multipart()
msg2 = pickle.loads(msg)
print msg2['game']