RabbitMQ : Use on Python2025/10/10 |
|
This is an example to use RabbitMQ on Python. |
|
| [1] | Install AMQP client library. |
|
root@dlp:~# apt -y install python3-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]. |
|
debian@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()
python3 send_msg.py [x] Sent 'Hello_World' |
| [3] | This is an example of receiving message on Python. |
|
debian@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()
python3 receive_msg.py [*] Waiting for messages. To exit press CTRL+C [x] Received b'Hello RabbitMQ World!' |
| Sponsored Link |
|
|