pyzmq的4种模式(PUB/SUB)笔记 博客分类: python pythonzmq
程序员文章站
2024-02-23 12:20:52
...
Pub/Sub pattern 发布/订阅模式
发布订阅模式:发布方不用管理发布给哪个订阅方(看到这句话感觉不太好),有2种场景
场景2比较常见,多客户端向一个服务端订阅,场景1类似与REP/REQ的多服务器模式,避免单个PUB撑不住,(2个PUB的数据都能收到)
pub-server.py
port = '5556' pub_server_name = 'pub-server01' context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind('tcp://*:%s'%port) while True: topic = random.randrange(9999,10005) messagedata = random.randrange(1,215)-80 print 'topic:%s messagedata:%s'%(topic,messagedata) socket.send('%d %d %s'%(topic,messagedata,pub_server_name)) time.sleep(1)
随机发送主题为9999-10005的数据
sub-client.py
#coding=utf-8 import sys import zmq port = "5556" if len(sys.argv) > 1: port = sys.argv[1] int(port) if len(sys.argv) > 2: port1 = sys.argv[2] int(port1) # Socket to talk to server context = zmq.Context() socket = context.socket(zmq.SUB) print "Collecting updates from weather server..." socket.connect ("tcp://localhost:%s" % port) if len(sys.argv) > 2: socket.connect ("tcp://localhost:%s" % port1) # 本地过滤 topicfilter = "10001" socket.setsockopt(zmq.SUBSCRIBE, topicfilter) # Process 5 updates total_value = 0 for update_nbr in range (5): string = socket.recv() topic, messagedata,pub_server_name = string.split() total_value += int(messagedata) print topic, messagedata,pub_server_name print "Average messagedata value for topic '%s' was %dF" % (topicfilter, total_value / update_nbr)
客户端只接收主题为10001的数据
PUB输出:
topic:10003 messagedata:7 topic:10000 messagedata:-27 topic:10000 messagedata:37 topic:10001 messagedata:-11 topic:10001 messagedata:-14 topic:9999 messagedata:38
client输出:
10001 -11pub-server01 10001 -14 pub-server01
另外:PUB/SUB是异步的,谁先开后开都行,就是说如果PUB已经开起来发送数据,然后SUB端起来,那么之前的那些数据SUB就收不到了,PUB和SUB逻辑上可以说是解耦的,二者不互相依赖。
最后是要点:
1.PUB未与SUB有逻辑上的连接,所以PUB可以很简单的drop掉数据(意思就是只管发)
2.如果你用的是TCP,然后SUB端要搞点什么比较慢,数据会Queue在PUB那头
3. 目前版本(最新版) filter(就是主题过滤)是在SUB端的,不是在PUB端,就是说SUB端比较苦逼,要全部收下一堆数据,再慢慢挑,这好像太那个了吧^_^