CentOS Stream 8
Sponsored Link

RabbitMQ : Python から利用する2021/06/21

 
RabbitMQ を Python から利用する例です。
[1] AMQP クライアントライブラリをインストールしておきます。
# EPEL からインストール

[root@dlp ~]#
dnf --enablerepo=epel -y install python3-pika
[2] Python スクリプトからのメッセージ送信例です。
例として、[localhost] で稼働する RabbitMQ サーバーに、RabbitMQ ユーザー [serverworld] , バーチャルホスト [my_vhost] へ接続して利用します。
[cent@dlp ~]$
vi send_msg.py
import pika

credentials = pika.PlainCredentials('serverworld', 'password')
connection = pika.BlockingConnection(pika.ConnectionParameters(
                                     'localhost',
                                     5672,
                                     '/my_vhost',
                                     credentials))

channel = connection.channel()
channel.queue_declare(queue='Hello_World')

channel.basic_publish(exchange='',
                      routing_key='Hello_World',
                      body='Hello RabbitMQ World!')

print(" [x] Sent 'Hello_World'")

connection.close()

[cent@dlp ~]$
python3 send_msg.py

 [x] Sent 'Hello_World'
[3] Python スクリプトからのメッセージ受信例です。
例として、上記 [2] で送信したメッセージを受信します。
[cent@node01 ~]$
vi receive_msg.py
import signal
import pika

signal.signal(signal.SIGPIPE, signal.SIG_DFL)
signal.signal(signal.SIGINT, signal.SIG_DFL)

credentials = pika.PlainCredentials('serverworld', 'password')
connection = pika.BlockingConnection(pika.ConnectionParameters(
                                     '10.0.0.30',
                                     5672,
                                     '/my_vhost',
                                     credentials))

channel = connection.channel()
channel.queue_declare(queue='Hello_World')

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

channel.basic_consume('Hello_World', callback, auto_ack=True)

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

[cent@node01 ~]$
python3 receive_msg.py

 [*] Waiting for messages. To exit press CTRL+C
 [x] Received b'Hello RabbitMQ World!'
関連コンテンツ