Chinaunix首页 | 论坛 | 博客
  • 博客访问: 783201
  • 博文数量: 239
  • 博客积分: 60
  • 博客等级: 民兵
  • 技术积分: 1045
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-22 18:25
文章分类

全部博文(239)

文章存档

2019年(9)

2018年(64)

2017年(2)

2016年(26)

2015年(30)

2014年(41)

2013年(65)

2012年(2)

分类: 架构设计与优化

2018-07-31 20:46:14

https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/_images/pushpull.png
参考
1)resultcollector.py

点击(此处)折叠或打开

  1. import time
  2. import zmq
  3. import pprint

  4. def result_collector():
  5.     context = zmq.Context()
  6.     results_receiver = context.socket(zmq.PULL)
  7.     results_receiver.bind("tcp://127.0.0.1:5558")
  8.     collecter_data = {}
  9.     for x in range(1,20000):
  10.         result = results_receiver.recv_json()
  11.         if result['consumer'] in collecter_data:
  12.             collecter_data[result['consumer']] = collecter_data[result['consumer']] + 1
  13.         else:
  14.             collecter_data[result['consumer']] = 1
  15.         if x == 999:
  16.             pprint.pprint(collecter_data)

  17. result_collector()


2)producer.py

点击(此处)折叠或打开

  1. import time
  2. import zmq

  3. def producer():
  4.     context = zmq.Context()
  5.     zmq_socket = context.socket(zmq.PUSH)
  6.     zmq_socket.bind("tcp://127.0.0.1:5557")
  7.     # Start your result manager and workers before you start your producers
  8.     for num in range(1,20000):
  9.         work_message = { 'num' : num }
  10.         zmq_socket.send_json(work_message)

  11. producer()


3)consumer.py

点击(此处)折叠或打开

  1. import time
  2. import zmq
  3. import random

  4. def consumer():
  5.     consumer_id = random.randrange(1,10005)
  6.     print ("I am consumer #%s" % (consumer_id))
  7.     context = zmq.Context()
  8.     # recieve work
  9.     consumer_receiver = context.socket(zmq.PULL)
  10.     consumer_receiver.connect("tcp://127.0.0.1:5557")
  11.     # send work
  12.     consumer_sender = context.socket(zmq.PUSH)
  13.     consumer_sender.connect("tcp://127.0.0.1:5558")

  14.     while True:
  15.         work = consumer_receiver.recv_json()
  16.         data = work['num']
  17.         result = { 'consumer' : consumer_id, 'num' : data}
  18.         if data%2 == 0:
  19.             consumer_sender.send_json(result)

  20. consumer()



#python3 resultcollector.py
#python3 producer.py
#python3 consumer.py
阅读(1621) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~