LoginSignup
1
5

More than 3 years have passed since last update.

RabbitMQをPython3から利用する。

Last updated at Posted at 2018-01-27

RabbitMQのインストール

インスト―ル
yum install rabbitmq-server.noarch

RabbitMQの起動

インスト―ル
systemctl start rabbitmq-server

プログラム実行環境インストール

インストール
yum install epel-release
yum install python34 python34-pip
pip3 install pika

プログラムを配置

send.py
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
recive.py
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue='hello',
                      auto_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

プログラム実行

※receive.py用のターミナルを起動して実行

receive.py実行
python34 receive.py

※send.py用のターミナルを起動して実行。

send.py実行
python34 send.py

実行結果

こんな感じになる。
①receive.py起動(キュー監視開始)

キュー監視開始
[root@devenv rabbitmq]# python34 receive.py
 [*] Waiting for messages. To exit press CTRL+C

②send.py起動(キュープッシュ)※何回か実行するといいかも。

キュープッシュ
[root@devenv rabbitmq]# python34 send.py
 [x] Sent 'Hello World!'

③キュー監視側はこうなる。

キュー監視側はキューがあると、自動で拾ってコンソールに表示する。
[root@devenv rabbitmq]# python receive.py
 [*] Waiting for messages. To exit press CTRL+C
 [x] Received b'Hello World!'
 [x] Received b'Hello World!'
 [x] Received b'Hello World!'
 [x] Received b'Hello World!'
1
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5