docker 创建rebbitmq
docker run -d --hostname my-rabbit --name some-rabbit
-e RABBITMQ_DEFAULT_USER=celery
-e RABBITMQ_DEFAULT_PASS=password123
-e RABBITMQ_DEFAULT_VHOST=my_vhost
-p 5672:5672 -p 15672:15672 rabbitmq:3.7.3-management
访问: http://localhost:15672/
生产者:send.py
import pika
credentials = pika.PlainCredentials('test', 'password') #用户名,密码
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='192.168.1.134', port=5672,virtual_host='my_vhost',credentials=credentials))
channel = connection.channel()
channel.queue_declare(queue = 'test')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
消费者:receiving.py
# -*- coding:utf-8 -*-
import pika
import traceback
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('config.ini')
#获取连接参数
HOST = cfg.get('config','HOST') #连接服务器ip
PORT = cfg.get('config','PORT') #连接服务端口号
VIRTUAL_HOST = cfg.get('config','VIRTUAL_HOST') #可访问虚拟主机
"""
# HOST = '192.168.1.134'
# PORT = 5672
# VIRTUAL_HOST = 'my_vhost'
"""
try:
credentials = pika.PlainCredentials('test', 'password') #用户名,密码
connection = pika.BlockingConnection(
pika.ConnectionParameters(host=HOST, port=PORT, virtual_host=VIRTUAL_HOST, credentials=credentials))
channel = connection.channel()
channel.queue_declare(queue='test')
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()
except Exception as e:
err = traceback.format_exc()
print(err)