RabbitMQ:python基础调用

前言

紧接上回在windows上安装了最新版的RabbitMQ:

RabbitMQ:windows最新版本4.0.5安装方案-CSDN博客

这是官方给出的使用文档:How to Use RabbitMQ | RabbitMQ

这里我给出通过AI学习到的python使用方法

理论截图

python直接使用pip安装pika模块即可开始使用RabbitMQ

复制代码
pip install pika

常用需要实现的队列模式

代码实现

话不多说,直接上代码

1、连接和关闭RabbitMQ服务

复制代码
import pika

# 创建连接
# 使用自定义的用户名和密码连接到 RabbitMQ
credentials = pika.PlainCredentials('manfish', '52manfish')
connection_params = pika.ConnectionParameters(
    host='localhost',  # RabbitMQ 服务器的主机名
    port=5672,         # RabbitMQ 的默认端口
    virtual_host='manfish',  # 虚拟主机名称
    credentials=credentials  # 认证凭证
)

connection = pika.BlockingConnection(connection_params)
channel = connection.channel()

# 声明队列json_queue
queue_name = 'json_queue'
channel.queue_declare(queue=queue_name)

# 关闭连接
connection.close()

注意:当不填写账号密码时,模块将自动以guest管理员默认账密(guest/guest)连接,不建议养成这种习惯

另:用户需要使用相同虚拟主机传递队列消息

这里是webui上设置账密及分配虚拟主机的截图:

2、直接队列

消费者
复制代码
import pika
import json

# 创建连接
# 使用自定义的用户名和密码连接到 RabbitMQ
credentials = pika.PlainCredentials('manfish1', '123456')
connection_params = pika.ConnectionParameters(
    host='localhost',  # RabbitMQ 服务器的主机名
    port=5672,         # RabbitMQ 的默认端口
    virtual_host='manfish1',  # 虚拟主机名称
    credentials=credentials  # 认证凭证
)

connection = pika.BlockingConnection(connection_params)
channel = connection.channel()

# 声明队列
queue_name = 'json_queue'
channel.queue_declare(queue=queue_name)

# 定义回调函数
def callback(ch, method, properties, body):
    print('------- get a msg -------')
    # 将 JSON 字符串反序列化为 Python 对象
    message_data = json.loads(body)
    print(f" [x] Received JSON message: {message_data}")

    # 打印 method 参数的详细信息
    print(f" [x] Delivery tag: {method.delivery_tag}")
    print(f" [x] Exchange: {method.exchange}")
    print(f" [x] Routing key: {method.routing_key}")
    print(f" [x] Redelivered: {method.redelivered}")

    # 打印 properties 参数的详细信息
    print(f" [x] Correlation ID: {properties.correlation_id}")
    print(f" [x] Content type: {properties.content_type}")
    print(f" [x] Headers: {properties.headers}")
    print(f" [x] Message ID: {properties.message_id}")
    print(f" [x] Timestamp: {properties.timestamp}")
    print(f" [x] User ID: {properties.user_id}")
    print(f" [x] App ID: {properties.app_id}")


# 开始消费
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
生产者
复制代码
import pika
import json

# 创建连接
credentials = pika.PlainCredentials('manfish', '123456')
connection_params = pika.ConnectionParameters(
    host='localhost',  # RabbitMQ 服务器的主机名
    port=5672,         # RabbitMQ 的默认端口
    virtual_host='manfish1',  # 虚拟主机名称
    credentials=credentials  # 认证凭证
)

connection = pika.BlockingConnection(connection_params)
channel = connection.channel()

# 声明队列
queue_name = 'json_queue'
channel.queue_declare(queue=queue_name)

# 创建一个 Python 字典
message_data = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
}

# 将字典转换为 JSON 字符串
message = json.dumps(message_data)

# 发送 JSON 数据
channel.basic_publish(
    exchange='',
    routing_key=queue_name,
    body=message
)
print(f" [x] Sent JSON message: {message}")

# 关闭连接
connection.close()
截图

3、主题队列

消费者
复制代码
import pika
import json

# 创建连接
# 使用自定义的用户名和密码连接到 RabbitMQ
credentials = pika.PlainCredentials('manfish1', '123456')
connection_params = pika.ConnectionParameters(
    host='localhost',  # RabbitMQ 服务器的主机名
    port=5672,         # RabbitMQ 的默认端口
    virtual_host='manfish1',  # 虚拟主机名称
    credentials=credentials  # 认证凭证
)

connection = pika.BlockingConnection(connection_params)
channel = connection.channel()

# 声明交换机
exchange_name = 'topic_exchange'
channel.exchange_declare(exchange=exchange_name, exchange_type='topic')

# 声明队列
result = channel.queue_declare('', exclusive=True)
queue_name = result.method.queue

# 绑定队列到交换机
binding_key = 'user.*'
channel.queue_bind(
    exchange=exchange_name,
    queue=queue_name,
    routing_key=binding_key
)

# 定义回调函数
def callback(ch, method, properties, body):
    print('------- get a msg -------')
    print(f" [x] Received message: {body}")

    # 打印 method 参数的详细信息
    print(f" [x] Delivery tag: {method.delivery_tag}")
    print(f" [x] Exchange: {method.exchange}")
    print(f" [x] Routing key: {method.routing_key}")
    print(f" [x] Redelivered: {method.redelivered}")

    # 打印 properties 参数的详细信息
    print(f" [x] Correlation ID: {properties.correlation_id}")
    print(f" [x] Content type: {properties.content_type}")
    print(f" [x] Headers: {properties.headers}")
    print(f" [x] Message ID: {properties.message_id}")
    print(f" [x] Timestamp: {properties.timestamp}")
    print(f" [x] User ID: {properties.user_id}")
    print(f" [x] App ID: {properties.app_id}")

    # 确认消息
    ch.basic_ack(delivery_tag=method.delivery_tag)

# 开始消费
# auto_ack为True时自动确认消息,但既为True又在回调中使用了ch.basic_ack(),则会导致报错------重复确认
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
生产者
复制代码
import time

import pika
import json

# 创建连接
credentials = pika.PlainCredentials('manfish', '123456')
connection_params = pika.ConnectionParameters(
    host='localhost',  # RabbitMQ 服务器的主机名
    port=5672,         # RabbitMQ 的默认端口
    virtual_host='manfish1',  # 虚拟主机名称
    credentials=credentials  # 认证凭证
)

connection = pika.BlockingConnection(connection_params)
channel = connection.channel()

# 声明交换机
exchange_name = 'topic_exchange'
channel.exchange_declare(exchange=exchange_name, exchange_type='topic')

# 发送消息
routing_key = 'user.login'
message = 'User logged in.'
channel.basic_publish(
    exchange=exchange_name,
    routing_key=routing_key,
    body=message,

)
print(f" [x] Sent message: {message}")

# 关闭连接
connection.close()
截图
相关推荐
Learn-Python5 小时前
MongoDB-only方法
python·sql
小途软件5 小时前
用于机器人电池电量预测的Sarsa强化学习混合集成方法
java·人工智能·pytorch·python·深度学习·语言模型
扫地的小何尚6 小时前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
wanglei2007086 小时前
生产者消费者
开发语言·python
清水白石0087 小时前
《从零到进阶:Pydantic v1 与 v2 的核心差异与零成本校验实现原理》
数据库·python
昵称已被吞噬~‘(*@﹏@*)’~7 小时前
【RL+空战】学习记录03:基于JSBSim构造简易空空导弹模型,并结合python接口调用测试
开发语言·人工智能·python·学习·深度强化学习·jsbsim·空战
Yeats_Liao7 小时前
MindSpore开发之路(二十四):MindSpore Hub:快速复用预训练模型
人工智能·分布式·神经网络·机器学习·个人开发
2501_941877987 小时前
从配置热更新到运行时自适应的互联网工程语法演进与多语言实践随笔分享
开发语言·前端·python
酩酊仙人7 小时前
fastmcp构建mcp server和client
python·ai·mcp
且去填词8 小时前
DeepSeek API 深度解析:从流式输出、Function Calling 到构建拥有“手脚”的 AI 应用
人工智能·python·语言模型·llm·agent·deepseek