Skip to content

ansmirnov/python-rabbitmq-hello-world

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RabbitMQ basic usage

Contents

Environment description

  • Deployed RabbitMQ 3.8.11
  • Python 3.9.1

Python requirements

pika==1.1.0

Producer

Imports

import os
import pika

Parameters

RABBITMQ_HOST = os.environ.get("RABBITMQ_HOST")
RABBITMQ_USER = os.environ.get("RABBITMQ_USER")
RABBITMQ_PASSWORD = os.environ.get("RABBITMQ_PASSWORD")

Creds

credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)

Connection

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host=RABBITMQ_HOST, credentials=credentials)
)

Channel

channel = connection.channel()

Declare queue

channel.queue_declare(queue='hello')

Publish message

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')

Close connection

connection.close()

Consumer

Imports

import os
import pika

Parameters

RABBITMQ_HOST = os.environ.get("RABBITMQ_HOST")
RABBITMQ_USER = os.environ.get("RABBITMQ_USER")
RABBITMQ_PASSWORD = os.environ.get("RABBITMQ_PASSWORD")

Creds

credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)

Connection

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host=RABBITMQ_HOST, credentials=credentials)
)

Channel

channel = connection.channel()

Declare queue

channel.queue_declare(queue='hello')

Callback

def callback(ch, method, properties, body):
    print("Received %r" % body)

Set callback

channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)

Start consuming

channel.start_consuming()

References

  1. https://www.rabbitmq.com/tutorials/tutorial-one-python.html