这个方法的签名如下:
def get_connection(
host='127.0.0.1',
port=5672,
username="zhangdapeng",
password="zhangdapeng520",
virtual_host='/',
):
"""
获取RabbitMQ客户端连接对象
:param host: 主机地址
:param port: 端口好
:param username: 用户名
:param password: 密码
:param virtual_host: 虚拟路径
:return: 连接对象
"""
有了这个方法以后,假如你的参数和这个方法的默认参数是相同或者相似的,获取连接会变得更加的简单。
import json
import rabbitmq
# 建立连接
connection = rabbitmq.get_connection()
# 创建管道
channel = connection.channel()
# 创建队列
queue_name = "user_manager"
result = channel.queue_declare(queue=queue_name)
# 向队列中写入数据
data = [
{"id": 1, "name": "张三", "age": 23},
{"id": 2, "name": "李四", "age": 24},
{"id": 3, "name": "王五", "age": 35},
]
for user in data:
message = json.dumps(user, ensure_ascii=True)
# 向队列插入数值 routing_key是队列名
channel.basic_publish(exchange='', routing_key=queue_name, body=message.encode('utf8'))
print(message)
# 关闭连接
connection.close()
import json
import rabbitmq
# 创建连接
connection = rabbitmq.get_connection()
# 创建管道
channel = connection.channel()
# 创建队列
queue_name = "user_manager"
channel.queue_declare(queue=queue_name, durable=False)
def callback(ch, method, properties, body):
# 解析队列中的每一条数据
ch.basic_ack(delivery_tag=method.delivery_tag)
data = body.decode("utf8")
print(json.loads(data))
# 告诉rabbitmq,用callback来接收消息
channel.basic_consume(queue_name, callback)
# 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
try:
channel.start_consuming()
finally:
connection.close()