Hello World by RabbitMQ in Python
环境
Today: 2019/04/02
Ubuntu – 18.04
RabbitMQ – 3.6.10
apt install erlang erlang-nox
apt install rabbitmq-server --fix-missing
sudo rabbitmqctl status
Python – 3.6.7
pika – 1.0.0
pip install --user pika
Hello World
send
#!/usr/bin/env python3
import sys
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
try:
msg = sys.argv[1]
except:
msg = "Hello World!"
channel.basic_publish(
exchange='',
routing_key='hello',
body=msg)
print(" [x] Sent '{}'".format(msg))
connection.close()
receive
#!/usr/bin/env python3
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
body = body.decode()
if body == "quit":
ch.basic_cancel(consumer_tag='hello')
ch.stop_consuming()
else:
print(" [x] Received %r" % body)
channel.basic_consume(
queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages......')
print('\tTo exit press CTRL+C, or send "quit" message')
channel.start_consuming()