zeroMQ初体验-9.优雅的扩展(代理模式)
前面所谈到的网络拓扑结构都是这样的:
而在实际的应用中,绝大多数会出现这样的结构要求:
zeroMQ中自然也提供了这样的需求案例:
1.发布/订阅 代理模式:
import zmqcontext = zmq.Context()frontend = context.socket(zmq.SUB)frontend.connect("tcp://192.168.55.210:5556")backend = context.socket(zmq.PUB)backend.bind("tcp://10.1.1.0:8100")frontend.setsockopt(zmq.SUBSCRIBE, '')while True: while True: message = frontend.recv() more = frontend.getsockopt(zmq.RCVMORE) if more: backend.send(message, zmq.SNDMORE) else: backend.send(message) break # Last message part
import zmqcontext = zmq.Context()socket = context.socket(zmq.REQ)socket.connect("tcp://localhost:5559")for request in range(1,10): socket.send("Hello") message = socket.recv() print "Received reply ", request, "[", message, "]"
import zmqcontext = zmq.Context()socket = context.socket(zmq.REP)socket.connect("tcp://localhost:5560")while True: message = socket.recv() print "Received request: ", message socket.send("World")
import zmqcontext = zmq.Context()frontend = context.socket(zmq.XREP)backend = context.socket(zmq.XREQ)frontend.bind("tcp://*:5559")backend.bind("tcp://*:5560")poller = zmq.Poller()poller.register(frontend, zmq.POLLIN)poller.register(backend, zmq.POLLIN)while True: socks = dict(poller.poll()) if socks.get(frontend) == zmq.POLLIN: message = frontend.recv() more = frontend.getsockopt(zmq.RCVMORE) if more: backend.send(message, zmq.SNDMORE) else: backend.send(message) if socks.get(backend) == zmq.POLLIN: message = backend.recv() more = backend.getsockopt(zmq.RCVMORE) if more: frontend.send(message, zmq.SNDMORE) else: frontend.send(message)
import zmqdef main(): context = zmq.Context(1) frontend = context.socket(zmq.XREP) frontend.bind("tcp://*:5559") backend = context.socket(zmq.XREQ) backend.bind("tcp://*:5560") zmq.device(zmq.QUEUE, frontend, backend) frontend.close() backend.close() context.term() if __name__ == "__main__": main()