ZMQ (如下 ZeroMQ 簡稱 ZMQ)是一個簡單好用的傳輸層,像框架同樣的一個 socket library,他使得 Socket 編程更加簡單、簡潔和性能更高。是一個消息處理隊列庫,可在多個線程、內核和主機盒之間彈性伸縮。ZMQ 的明確目標是「成爲標準網絡協議棧的一部分,以後進入 Linux 內核」。如今還未看到它們的成功。可是,它無疑是極具前景的、而且是人們更加須要的「傳統」BSD 套接字之上的一層封裝。ZMQ 讓編寫高性能網絡應用程序極爲簡單和有趣。
zeromq
並非相似rabbitmq
消息列隊,它實際上只一個消息列隊組件,一個庫。python
客戶端在請求後,服務端必須迴響應
Python實現:
server端:編程
# -*- coding=utf-8 -*- import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5555") while True: message = socket.recv() print("Received: %s" % message) socket.send("I am OK!")
client端:緩存
# -*- coding=utf-8 -*- import zmq import sys context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:5555") socket.send('Are you OK?') response = socket.recv(); print("response: %s" % response)
輸出:bash
$ python app/server.py Received: Are you OK? $ python app/client1.py response: I am OK!
廣播全部client,沒有隊列緩存,斷開鏈接數據將永遠丟失。client能夠進行數據過濾。
網絡
Python實現
server端:app
# -*- coding=utf-8 -*- import zmq import time context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:5555") while True: print('發送消息') socket.send("消息羣發") time.sleep(1)
client端1:框架
# -*- coding=utf-8 -*- import zmq import sys context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://localhost:5555") socket.setsockopt(zmq.SUBSCRIBE,'') # 消息過濾 while True: response = socket.recv(); print("response: %s" % response)
client端2:socket
# -*- coding=utf-8 -*- import zmq import sys context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://localhost:5555") socket.setsockopt(zmq.SUBSCRIBE,'') while True: response = socket.recv(); print("response: %s" % response)
輸出:tcp
$ python app/server.py 發送消息 發送消息 發送消息 $ python app/client2.py response: 消息羣發 response: 消息羣發 response: 消息羣發 $ python app/client1.py response: 消息羣發 response: 消息羣發 response: 消息羣發
由三部分組成,push進行數據推送,work進行數據緩存,pull進行數據競爭獲取處理。區別於Publish-Subscribe存在一個數據緩存和處理負載。性能
當鏈接被斷開,數據不會丟失,重連後數據繼續發送到對端。
Python實現
server端:
# -*- coding=utf-8 -*- import zmq import time context = zmq.Context() socket = context.socket(zmq.PUSH) socket.bind("tcp://*:5557") while True: socket.send("測試消息") print "已發送" time.sleep(1)
work端:
# -*- coding=utf-8 -*- import zmq context = zmq.Context() recive = context.socket(zmq.PULL) recive.connect('tcp://127.0.0.1:5557') sender = context.socket(zmq.PUSH) sender.connect('tcp://127.0.0.1:5558') while True: data = recive.recv() print "正在轉發..." sender.send(data)
client端:
# -*- coding=utf-8 -*- import zmq import sys context = zmq.Context() socket = context.socket(zmq.PULL) socket.bind("tcp://*:5558") while True: response = socket.recv(); print("response: %s" % response)
輸出結果:
$ python app/server.py 已發送 已發送 已發送 $ python app/work.py 正在轉發... 正在轉發... 正在轉發... $ python app/client1.py response: 測試消息 response: 測試消息 response: 測試消息