1. 生产者 send.py

import pika

USER = "admin"
PWD = "admin"
connection = pika.BlockingConnection(pika.ConnectionParameters(host='120.76.250.234', credentials=pika.PlainCredentials(USER, PWD)))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

2. 消费者 receive.py

#!/usr/bin/env python
import pika, sys, os

def main():
USER = "admin"
PWD = "admin"
connection = pika.BlockingConnection(pika.ConnectionParameters(host='120.76.250.234', credentials=pika.PlainCredentials(USER, PWD)))
channel = connection.channel()

channel.queue_declare(queue='hello')

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

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

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)

3. 运行

python3 send.py
python3 receive.py

4. 结果

RabbitMQ management 地址: http://120.76.250.234:15672 admin admin

RabbitMQ 生产者和消费者 Hello World_RabbitMQ


RabbitMQ 生产者和消费者 Hello World_消息队列_02