學了saltstack有一段時間了,說實話,對於一個python愛好者來講salt源代碼真是一個寶藏啊。因而乎去看了源代碼,發現全部問題都卡在了底層通訊上,在看saltstack以前都不知道有一個這麼好的zeromq通訊協議。如今就來記錄關於zeromq的學習筆記。
python
zmq是什麼:zmq是基於以前協議(tcp,ipc,inproc)開發的併發框架,採用異步IO非阻塞方式,多對多的通訊模式,無需在乎服務端和客戶端的啓動順序。它包含四種通訊模式:PAIR/PAIR,REP/REQ,PUB/SUB,PUSH/PULL。其餘模式都是基於這四種混合使用的。併發
PAIR/PAIR:一對一的請求,跟普通socket相似,這種模式通常不會用。負載均衡
代碼以下:框架
server.pydom
import zmq import random import sys import time port = "5556" context = zmq.Context() socket = context.socket(zmq.PAIR) socket.bind("tcp://*:%s" % port) while True: socket.send("Server message to client3") msg = socket.recv() if msg == 'EOF': break print msg time.sleep(1)
client.py異步
import zmq import random import sys import time port = "5556" context = zmq.Context() socket = context.socket(zmq.PAIR) socket.connect("tcp://localhost:%s" % port) for i in range(5): msg = socket.recv() print msg socket.send("client message to server1") time.sleep(1) socket.send("EOF")
zmq有個好處,就是無需在乎server和client的啓動順序。執行這兩個腳本。
socket
REP/REQ:請求應答模式,是多對多模式,這個模式必須遵循必定的順序,且recv和send是成對存在的。客戶端首先必須send一個請求再recv響應,服務端必須recv一個請求再send響應。這種模式能夠用於負載均衡。tcp
reqrep_server.py
ide
import zmq import time import sys port = "5556" if len(sys.argv) > 1: port = sys.argv[1] int(port) context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:%s" % port) while True: # Wait for next request from client try: message = socket.recv() print "Received request: ", message time.sleep (1) socket.send("World from %s:%s" % ('192.168.79.49',port)) except KeyboardInterrupt: break
repreq_client.py學習
import zmq import sys port = "5556" if len(sys.argv) > 1: port = sys.argv[1] int(port) if len(sys.argv) > 2: port1 = sys.argv[2] int(port1) context = zmq.Context() print "Connecting to server..." socket = context.socket(zmq.REQ) socket.connect ("tcp://localhost:%s" % port) if len(sys.argv) > 2: socket.connect ("tcp://localhost:%s" % port1) for request in range (1,10): print "Sending request ", request,"..." socket.send ("Hello") # Get the reply. message = socket.recv() print "Received reply ", request, "[", message, "]"
python reqrep_server.py 5555
python reqrep_server.py 5556
python reqrep_client.py 5555 5556
執行這三個命令,請求會均衡的發到兩個服務端。