zeroMQ初體驗-3.分而治之模式(push/pull)

 
push/pull模式:



模型描述:
1.上游(任務發佈)
2.工人(中間,具體工作)
3.下游(信號採集或者工作結果收集)

上游代碼:
Python代碼
import zmq
import random
import time

context = zmq.Context()

# Socket to send messages on
sender = context.socket(zmq.PUSH)
sender.bind("tcp://*:5557")

print "Press Enter when the workers are ready: "
_ = raw_input()
print "Sending tasks to workers..."

# The first message is "0" and signals start of batch
sender.send('0')

# Initialize random number generator
random.seed()

# Send 100 tasks
total_msec = 0
for task_nbr in range(100):
    # Random workload from 1 to 100 msecs
    workload = random.randint(1, 100)
    total_msec += workload
    sender.send(str(workload))
print "Total expected cost: %s msec" % total_msec


工作代碼:
Python代碼
import sys
import time
import zmq

context = zmq.Context()

# Socket to receive messages on
receiver = context.socket(zmq.PULL)
receiver.connect("tcp://localhost:5557")

# Socket to send messages to
sender = context.socket(zmq.PUSH)
sender.connect("tcp://localhost:5558")

# Process tasks forever
while True:
    s = receiver.recv()

    # Simple progress indicator for the viewer
    sys.stdout.write('.')
    sys.stdout.flush()

    # Do the work
    time.sleep(int(s)*0.001)

    # Send results to sink
    sender.send('')


下游代碼:
Python代碼
import sys
import time
import zmq

context = zmq.Context()

# Socket to receive messages on
receiver = context.socket(zmq.PULL)
receiver.bind("tcp://*:5558")

# Wait for start of batch
s = receiver.recv()

# Start our clock now
tstart = time.time()

# Process 100 confirmations
total_msec = 0
for task_nbr in range(100):
    s = receiver.recv()
    if task_nbr % 10 == 0:
        sys.stdout.write(':')
    else:
        sys.stdout.write('.')

# Calculate and report duration of batch
tend = time.time()
print "Total elapsed time: %d msec" % ((tend-tstart)*1000)



注意點:
這種模式與pub/sub模式一樣都是單向的,區別有兩點:
1,該模式下在沒有消費者的情況下,發佈者的信息是不會消耗的(由發佈者進程維護)
2,多個消費者消費的是同一列信息,假設A得到了一條信息,則B將不再得到

這種模式主要針對在消費者能力不夠的情況下,提供的多消費者並行消費解決方案(也算是之前的pub/sub模式的那個"堵塞問題"的一個解決策略吧)

由上面的模型圖可以看出,這是一個N:N的模式,在1:N的情況下,各消費者並不是平均消費的,而在N:1的情況下,則有所不同,如下圖:



這種模式主要關注點在於,可以擴展中間worker,來到達併發的目的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章