ZeroMQ with producer-consumer


</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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值