码迷,mamicode.com
首页 > 其他好文 > 详细

ZeroMQ with producer-consumer

时间:2015-04-09 17:36:26      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:


</step00>


Make sure what you need !

Let‘s see the map below:

技术分享


</step01> If your data centre send many many data to you by socket ...


Let‘s see the map again ..


技术分享


</step02> So you may know how to use the ZeroMQ deal with your data ...


We assume the the socket.recv just like a client ...(Actually,it‘s server/client )


So the code can be like the below ...


</pre><pre name="code" class="python">#!/usr/bin/python

import zmq 

import time

context = zmq.Context()

socket = context.socket(zmq.REQ)

socket.connect("tcp://localhost:5559")

for request in range(1,11):
    
        socket.send(b"Hello:-->%d" % request)

        message = socket.recv()

        print("Received reply %s [%s]" % (request,message))

        time.sleep(1)


</step03> Here,You have the data source ... But where is the ZeroMQ ..

Good ! let‘s create one ,Because it‘s work like a broker , so we name it as "broker.py"


#!/usr/bin/python

import zmq

context = zmq.Context()

frontend = zmq.Context()

frontend = context.socket(zmq.ROUTER)

backend = context.socket(zmq.DEALER)

frontend.bind("tcp://*:5559")

backend.bind("tcp://*:5560")

poller = zmq.Poller()

poller.register(frontend,zmq.POLLIN)

poller.register(backend,zmq.POLLIN)

while True:

        socks = dict(poller.poll())

        if socks.get(frontend) == zmq.POLLIN:

                message = frontend.recv_multipart()

                backend.send_multipart(message)

        if socks.get(backend) == zmq.POLLIN:

                message = backend.recv_multipart()

                frontend.send_multipart(message)


</step04> we have a broker ,so He/She looking for someone work for him/her ....

Here,We will hire some worker ...(Actually,We make them ...)

How to make it ...Let‘s see the code below 


#!/usr/bin/python

import zmq

context = zmq.Context()

frontend = zmq.Context()

frontend = context.socket(zmq.ROUTER)

backend = context.socket(zmq.DEALER)

frontend.bind("tcp://*:5559")

backend.bind("tcp://*:5560")

poller = zmq.Poller()

poller.register(frontend,zmq.POLLIN)

poller.register(backend,zmq.POLLIN)

while True:

        socks = dict(poller.poll())

        if socks.get(frontend) == zmq.POLLIN:

                message = frontend.recv_multipart()

                backend.send_multipart(message)

        if socks.get(backend) == zmq.POLLIN:

                message = backend.recv_multipart()

                frontend.send_multipart(message)


</step05>


That‘s all !  Thanks :)


Ref:http://zguide.zeromq.org/page:all

ZeroMQ with producer-consumer

标签:

原文地址:http://blog.csdn.net/u011767611/article/details/44960941

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!