FreeBSD 14
Sponsored Link

RabbitMQ : Use on Python2024/09/17

 

This is an example to use RabbitMQ on Python.

[1] Install AMQP client library.
root@dlp:~ #
pkg install -y py311-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].
freebsd@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()

freebsd@dlp:~ $
python3.11 send_msg.py

 [x] Sent 'Hello_World'
[3] This is an example of receiving message on Python.
freebsd@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()

freebsd@node01:~ $
python3.11 receive_msg.py

 [*] Waiting for messages. To exit press CTRL+C
 [x] Received b'Hello RabbitMQ World!'
Matched Content