秋风阁-北溪入江流
version: '3.8'
services:
rabbitmq:
image: rabbitmq:3.11.19
container_name: rabbitmq
hostname: rabbitmq
ports:
# amqp协议通讯端口(对外服务必开)
- 5672:5672
# RabbitMq自带管理界面访问端口
- 15672:15672
environment:
- RABBITMQ_DEFAULT_VHOST=${vhost}
- RABBITMQ_DEFAULT_USER=${user}
- RABBITMQ_DEFAULT_PASS=${password}
RabbitMq自带有专门的管理界面,可以在其管理界面对RabbitMq进行管理查看等操作。
RabbitMq的管理界面的对外端口为15672
,当我们启动RabbitMq后,需要启动管理界面插件后才能访问界面。
# 进入容器内部
docker exec -it rabbitmq bash
# 启动插件,启动管理界面
rabbitmq-plugins enable rabbitmq_management
pika
pip install pika
# 连接RabbitMq
connect = pika.BlockingConnection(pika.URLParameters("amqp://${user}:${password}@${ip}:${port}/${vhost}"))
# 创建通讯信道
channel = connect.channel()
# 创建(声明)消息队列,该方法在没有队列时会主动创建队列
channel.queue_declare(queue=${queue_name})
# 关闭RabbitMq连接
channel.close()
connect.close()
channel.basic_publish(exchange="", routing_key=${queue_name}, body=f"你好 World!".encode(encoding="UTF-8"))
import pika
connect = pika.BlockingConnection(pika.URLParameters("amqp://${user}:${password}@${ip}:${port}/${vhost}"))
channel = connect.channel()
channel.queue_declare(queue=${queue_name})
channel.basic_publish(exchange="", routing_key=${queue_name}, body=f"你好 World!".encode(encoding="UTF-8"))
channel.close()
connect.close()
def callback(channel, method, properties, body: bytes):
"""
自定义回调函数
:param channel: BlockingChannel
:param method: spec.Basic.Deliver
:param properties: spec.BasicProperties
:param body: bytes
"""
print(f"消费者接收数据: {body.decode('UTF-8')}")
# 绑定消息队列,接收数据
channel.basic_consume(queue=${queue_name}, auto_ack=True, on_message_callback=callback)
# 阻塞函数,启动后会一直运行等待发布者发送数据
channel.start_consuming()
import pika
connect = pika.BlockingConnection(pika.URLParameters("amqp://${user}:${password}@${ip}:${port}/${vhost}"))
channel = connect.channel()
channel.queue_declare(queue=${queue_name})
def callback(channel, method, properties, body: bytes):
"""
自定义回调函数
:param channel: BlockingChannel
:param method: spec.Basic.Deliver
:param properties: spec.BasicProperties
:param body: bytes
"""
print(f"消费者接收数据: {body.decode('UTF-8')}")
# 绑定消息队列,接收数据
channel.basic_consume(queue=${queue_name}, auto_ack=True, on_message_callback=callback)
# 阻塞函数,启动后会一直运行等待发布者发送数据
channel.start_consuming()