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

http://iyuan.iteye.com/blog/974040

push/pull模式: 

 

模型描述: 
1.上游(任务发布) 
2.工人(中间,具体工作) 
3.下游(信号采集或者工作结果收集) 

上游代码: 

Python代码  收藏代码
  1. import zmq  
  2. import random  
  3. import time  
  4.   
  5. context = zmq.Context()  
  6.   
  7. # Socket to send messages on  
  8. sender = context.socket(zmq.PUSH)  
  9. sender.bind("tcp://*:5557")  
  10.   
  11. print "Press Enter when the workers are ready: "  
  12. _ = raw_input()  
  13. print "Sending tasks to workers..."  
  14.   
  15. # The first message is "0" and signals start of batch  
  16. sender.send('0')  
  17.   
  18. # Initialize random number generator  
  19. random.seed()  
  20.   
  21. # Send 100 tasks  
  22. total_msec = 0  
  23. for task_nbr in range(100):  
  24.     # Random workload from 1 to 100 msecs  
  25.     workload = random.randint(1, 100)  
  26.     total_msec += workload  
  27.     sender.send(str(workload))  
  28. print "Total expected cost: %s msec" % total_msec  



工作代码: 

Python代码  收藏代码
  1. import sys  
  2. import time  
  3. import zmq  
  4.   
  5. context = zmq.Context()  
  6.   
  7. # Socket to receive messages on  
  8. receiver = context.socket(zmq.PULL)  
  9. receiver.connect("tcp://localhost:5557")  
  10.   
  11. # Socket to send messages to  
  12. sender = context.socket(zmq.PUSH)  
  13. sender.connect("tcp://localhost:5558")  
  14.   
  15. # Process tasks forever  
  16. while True:  
  17.     s = receiver.recv()  
  18.   
  19.     # Simple progress indicator for the viewer  
  20.     sys.stdout.write('.')  
  21.     sys.stdout.flush()  
  22.   
  23.     # Do the work  
  24.     time.sleep(int(s)*0.001)  
  25.   
  26.     # Send results to sink  
  27.     sender.send('')  



下游代码: 

Python代码  收藏代码
  1. import sys  
  2. import time  
  3. import zmq  
  4.   
  5. context = zmq.Context()  
  6.   
  7. # Socket to receive messages on  
  8. receiver = context.socket(zmq.PULL)  
  9. receiver.bind("tcp://*:5558")  
  10.   
  11. # Wait for start of batch  
  12. s = receiver.recv()  
  13.   
  14. # Start our clock now  
  15. tstart = time.time()  
  16.   
  17. # Process 100 confirmations  
  18. total_msec = 0  
  19. for task_nbr in range(100):  
  20.     s = receiver.recv()  
  21.     if task_nbr % 10 == 0:  
  22.         sys.stdout.write(':')  
  23.     else:  
  24.         sys.stdout.write('.')  
  25.   
  26. # Calculate and report duration of batch  
  27. tend = time.time()  
  28. print "Total elapsed time: %d msec" % ((tend-tstart)*1000)  




注意点: 
这种模式与pub/sub模式一样都是单向的,区别有两点: 
1,该模式下在没有消费者的情况下,发布者的信息是不会消耗的(由发布者进程维护) 
2,多个消费者消费的是同一列信息,假设A得到了一条信息,则B将不再得到 

这种模式主要针对在消费者能力不够的情况下,提供的多消费者并行消费解决方案(也算是之前的pub/sub模式的那个"堵塞问题"的一个解决策略吧) 

由上面的模型图可以看出,这是一个N:N的模式,在1:N的情况下,各消费者并不是平均消费的,而在N:1的情况下,则有所不同,如下图: 
 


这种模式主要关注点在于,可以扩展中间worker,来到达并发的目的。

posted @ 2015-05-21 19:47  jimshi  阅读(2671)  评论(0编辑  收藏  举报