CentOS Stream 9
Sponsored Link

RabbitMQ : Use on Python2022/07/14

 
This is an example to use RabbitMQ on Python.
[1] Install AMQP client library with any user who runs Python.
[cent@dlp ~]$
pip3 install pika
[2] This is an example of sending message on Python.
For example, connect with RabbitMQ on [localhost] with a user [serverworld], virtualhost [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] This is an example of receiving message on Python.
[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!'
Matched Content