RabbitMQ : Use on Python2016/09/03 |
This is an example to use RabbitMQ on Python.
|
|
[1] | Install AMQP client library. |
# install from EPEL [root@dlp ~]# yum --enablerepo=epel -y install python2-pika
|
[2] | This is an example of sending message on Python. For example, connect with RabbitMQ user "serverworld", virtualhost "my_vhost". |
[cent@dlp ~]$
vi send_msg.py #!/usr/bin/env python 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() python send_msg.py [x] Sent 'Hello_World' |
[3] | This is an example of receiving message on Python. |
[cent@node01 ~]$
vi receive_msg.py #!/usr/bin/env python 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( 'dlp.srv.world', 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(callback, queue='Hello_World', no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming() python receive_msg.py [*] Waiting for messages. To exit press CTRL+C [x] Received 'Hello RabbitMQ World!' |
Sponsored Link |