RabbitMQ python example

#Publish
import pika
#Credentials may not need
authS = pika.PlainCredentials('usename', 'password')
# new instance
connection = pika.BlockingConnection(
    pika.ConnectionParameters('localhost',5672, credentials=authS)  # default port
    )
# claim a pipe
channel = connection.channel()
# claim queue in pipe
channel.queue_declare(queue='hello')
# RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',
                      routing_key='hello',  # queue name
                      body='Hello World!')  # msg
print(" [x] Sent 'Hello World!'")
connection.close()  # close
#Consume
import pika
#Credentials may not need
authS = pika.PlainCredentials('usename', 'password')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost', credentials=authS))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
channel.basic_consume(callback, queue='hello', no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

LEAVE A COMMENT