我注意到 ZeroMQ 的 PUB 套接字在连接时会缓冲所有的传出数据,例如:
import zmq
import time
context = zmq.Context()
# create a PUB socket
pub = context.socket (zmq.PUB)
pub.connect("tcp://127.0.0.1:5566")
# push some message before connected
# they should be dropped
for i in range(5):
pub.send('a message should not be dropped')
time.sleep(1)
# create a SUB socket
sub = context.socket (zmq.SUB)
sub.bind("tcp://127.0.0.1:5566")
sub.setsockopt(zmq.SUBSCRIBE, "")
time.sleep(1)
# this is the only message we should see in SUB
pub.send('hi')
while True:
print sub.recv()
sub绑定在那些消息之后,它们应该被丢弃,因为如果没有人连接到PUB,它应该丢弃消息。但是,它不会丢弃消息,而是缓冲所有消息。
a message should not be dropped
a message should not be dropped
a message should not be dropped
a message should not be dropped
a message should not be dropped
hi
正如你所看到的,那些“消息不应该被丢弃”的消息会被套接字缓存,一旦连接成功,它们就会被刷新到 SUB 套接字。如果我在 PUB 套接字上绑定,并在 SUB 套接字上连接,则可以正常工作。
import zmq
import time
context = zmq.Context()
# create a PUB socket
pub = context.socket (zmq.PUB)
pub.bind("tcp://127.0.0.1:5566")
# push some message before connected
# they should be dropped
for i in range(5):
pub.send('a message should not be dropped')
time.sleep(1)
# create a SUB socket
sub = context.socket (zmq.SUB)
sub.connect("tcp://127.0.0.1:5566")
sub.setsockopt(zmq.SUBSCRIBE, "")
time.sleep(1)
# this is the only message we should see in SUB
pub.send('hi')
while True:
print repr(sub.recv())
你只能看到输出结果
'hi'
这种奇怪的行为会导致一个问题,它会缓存所有连接套接字上的数据。我有两个服务器,服务器A向服务器B发布数据。
Server A -- publish --> Server B
如果服务器B联机,那么它能够良好工作。但是,如果我启动服务器A而不启动服务器B呢?
结果是,连接到服务器A的PUB套接字会保留所有这些数据,内存使用量会变得越来越高。
问题在于,这种行为是bug还是feature?如果是feature,那么我该在哪里找到提到这种行为的文档?我如何停止连接的PUB套接字缓存所有数据?
谢谢。