読者です 読者をやめる 読者になる 読者になる

YAMAGUCHI::weblog

土足で窓から失礼いたします。今日からあなたの息子になります。 当年とって92歳、下町の発明王、エジソンです。

pyzmqでZeroMQを触ってみる (REQ/REP)

Python ZeroMQ

はじめに

こんにちは、Python界の情弱です。ZeroMQを使って色々やろうと思うことがあったので、ZeroMQのガイドをPython版でやってみることにした。

REQ/REP

コード

Hello World Server/Client

import zmq
import time

context = zmq.Context()
responder = context.socket(zmq.REP)
responder.bind("tcp://localhost:5555")

while True:
  request = responder.recv()
  print "recieved request: [%s]" % request
  time.sleep(1.0)
  responder.send("World at %s" % time.strftime("%Y-%m-%dT%H:%M:%S"))
import zmq
import sys

context = zmq.Context()

# Socket to talk to server
print "connecting to hello world server"
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")

for request in range(1, 100):
  print "sending request %d ..." % request
  socket.send("Hello from %s" % sys.argv[1]) # show client id

  message = socket.recv()
  print "received reply %d [ %s ]" % (request, message)
実行結果

まずhelloworldsrv.pyを起動

% python helloworldsrv.py

次に2つのクライアントをそれぞれ起動

% python helloworldcli.py 1
% python helloworldcli.py 2

すると

  • helloworldsrv.py
% python helloworldsrv.py
recieved request: [Hello from 1]
recieved request: [Hello from 1]
recieved request: [Hello from 1]
recieved request: [Hello from 2]
recieved request: [Hello from 1]
recieved request: [Hello from 2]
recieved request: [Hello from 1]
recieved request: [Hello from 2]
  • helloworldcli.py
% python helloworldcli.py 1
connecting to hello world server
sending request 1 ...
received reply 1 [ World at 2012-03-27T22:15:56 ]
sending request 2 ...
received reply 2 [ World at 2012-03-27T22:15:57 ]
sending request 3 ...
received reply 3 [ World at 2012-03-27T22:15:58 ]
sending request 4 ...
received reply 4 [ World at 2012-03-27T22:16:00 ]
sending request 5 ...
received reply 5 [ World at 2012-03-27T22:16:02 ]
% python helloworldcli.py 2
connecting to hello world server
sending request 1 ...
received reply 1 [ World at 2012-03-27T22:15:59 ]
sending request 2 ...
received reply 2 [ World at 2012-03-27T22:16:01 ]
sending request 3 ...
received reply 3 [ World at 2012-03-27T22:16:03 ]

しかし、Amazonで色々探してみたけど、メッセージキューを使った設計に関する本とかって和書は出てないんだね。企業とかで結構使ってると思うんだけど、みんなどうやってんのかね。

Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions (Addison-Wesley Signature Series (Fowler))

Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions (Addison-Wesley Signature Series (Fowler))