Queue device
这是一个位于客户端可服务端的中间件,拓展了之前的REQ/REP模式,图
通过这种方式,REQ socket和REP socket之间不需要明确绑定了,大家都绑定到Queue这个device就可以了,Queue device来处理请求的发送与返回,灵活度大大提升(不这样估计没人用),看看代码 Queue-device:
#coding=utf-8
import zmq
def main():
try:
context = zmq.Context(1)#IO线程数
# 面向客户端
frontend = context.socket(zmq.XREP)
frontend.bind("tcp://*:5559")
# 面向服务端
backend = context.socket(zmq.XREQ)
backend.bind("tcp://*:5560")
zmq.device(zmq.QUEUE, frontend, backend)
except Exception, e:
print e
print "bringing down zmq device"
finally:
pass
frontend.close()
backend.close()
context.term()#手动结束context
if __name__ == "__main__":
main()
好心的告诉你,zmq.device()里有个while True:,所以别担心它自己结束,作者挺细心的:)
Queue-server:这个就是普通的REP
import zmq
import time
import sys
import random
port = "5560"
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.connect("tcp://localhost:%s" % port)
server_id = random.randrange(1,10005)
while True:
# Wait for next request from client
message = socket.recv()
print "Received request: ", message
time.sleep (1)
socket.send("World from server %s" % server_id)
Queue-client:普通的REQ
import zmq
import sys
import random
port = "5559"
context = zmq.Context()
print "Connecting to server..."
socket = context.socket(zmq.REQ)
socket.connect ("tcp://localhost:%s" % port)
client_id = random.randrange(1,10005)
# Do 10 requests, waiting each time for a response
for request in range (1,10):
print "Sending request ", request,"..."
socket.send ("Hello from %s" % client_id)
# Get the reply.
message = socket.recv()
print "Received reply ", request, "[", message, "]"
run的顺序是Queue device先起来,然后server,client,一切如同之前的REQ/REP模式。
对应的还有2个device,大同小异,复制下图
PUB/SUB家的:
PUSH/PULL家的:
ok,接下来的似乎要深入点,总的来说感觉这个学习曲线还是很平滑的:)