消息队列:RabbitMQ与事件驱动架构

消息队列:RabbitMQ与事件驱动架构

大家好,我是欧阳瑞(Rich Own)。今天想和大家聊聊消息队列和事件驱动架构。作为一个全栈开发者,消息队列是构建高可用、可扩展系统的关键组件。今天就来分享一下RabbitMQ的使用经验。

什么是消息队列?

消息队列是一种异步通信机制,允许应用程序之间通过消息进行解耦。

为什么使用消息队列?

优势 说明
解耦 生产者和消费者解耦
异步处理 提高系统响应速度
削峰填谷 处理突发流量
可靠性 消息持久化保证

RabbitMQ入门

安装RabbitMQ

bash 复制代码
# 使用Docker安装
docker run -d --name rabbitmq \
  -p 5672:5672 \
  -p 15672:15672 \
  -e RABBITMQ_DEFAULT_USER=admin \
  -e RABBITMQ_DEFAULT_PASS=password \
  rabbitmq:3-management

基本概念

概念 说明
Producer 消息生产者
Consumer 消息消费者
Queue 消息队列
Exchange 交换机
Binding 绑定关系

核心模式

1. 简单队列

python 复制代码
# 生产者
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(
    exchange='',
    routing_key='hello',
    body='Hello World!'
)

connection.close()
python 复制代码
# 消费者
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(f"Received {body}")

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

channel.start_consuming()

2. 发布/订阅模式

python 复制代码
# 发布者
channel.exchange_declare(exchange='logs', exchange_type='fanout')

channel.basic_publish(
    exchange='logs',
    routing_key='',
    body='Hello World!'
)
python 复制代码
# 订阅者
channel.exchange_declare(exchange='logs', exchange_type='fanout')

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue

channel.queue_bind(exchange='logs', queue=queue_name)

def callback(ch, method, properties, body):
    print(f"Received {body}")

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

3. 路由模式

python 复制代码
# 生产者
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')

severity = 'error'
channel.basic_publish(
    exchange='direct_logs',
    routing_key=severity,
    body='Error message'
)
python 复制代码
# 消费者
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue

channel.queue_bind(
    exchange='direct_logs',
    queue=queue_name,
    routing_key='error'
)

4. 主题模式

python 复制代码
# 生产者
channel.exchange_declare(exchange='topic_logs', exchange_type='topic')

channel.basic_publish(
    exchange='topic_logs',
    routing_key='user.login.success',
    body='User logged in'
)
python 复制代码
# 消费者
channel.exchange_declare(exchange='topic_logs', exchange_type='topic')

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue

channel.queue_bind(
    exchange='topic_logs',
    queue=queue_name,
    routing_key='user.*.*'
)

实战案例:订单处理系统

python 复制代码
import pika
import json

# 订单创建服务
def create_order(order):
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    channel.exchange_declare(exchange='order_events', exchange_type='topic')
    
    channel.basic_publish(
        exchange='order_events',
        routing_key='order.created',
        body=json.dumps(order)
    )
    
    connection.close()

# 库存服务
def handle_inventory_update(ch, method, properties, body):
    order = json.loads(body)
    print(f"Updating inventory for order: {order['id']}")
    
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    channel.exchange_declare(exchange='order_events', exchange_type='topic')
    channel.basic_publish(
        exchange='order_events',
        routing_key='inventory.updated',
        body=json.dumps({'order_id': order['id']})
    )
    
    connection.close()

# 通知服务
def handle_notification(ch, method, properties, body):
    data = json.loads(body)
    print(f"Sending notification for order: {data['order_id']}")

最佳实践

1. 消息持久化

python 复制代码
channel.queue_declare(queue='orders', durable=True)

channel.basic_publish(
    exchange='',
    routing_key='orders',
    body='message',
    properties=pika.BasicProperties(
        delivery_mode=2  # 持久化消息
    )
)

2. 消息确认

python 复制代码
def callback(ch, method, properties, body):
    print(f"Processing {body}")
    
    # 处理完成后手动确认
    ch.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_consume(
    queue='orders',
    on_message_callback=callback,
    auto_ack=False  # 关闭自动确认
)

3. 消息重试

python 复制代码
def callback(ch, method, properties, body):
    try:
        process_message(body)
        ch.basic_ack(delivery_tag=method.delivery_tag)
    except Exception as e:
        # 重试3次后丢弃
        if method.delivery_tag < 3:
            ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
        else:
            ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)

总结

RabbitMQ是一个强大的消息队列系统,可以帮助你构建事件驱动的微服务架构。从简单队列到复杂的路由模式,RabbitMQ都能胜任。

我的鬃狮蜥Hash对消息队列也有自己的理解------它总是通过特定的信号找到蟋蟀,这也许就是自然界的"消息传递"吧!

如果你对消息队列感兴趣,欢迎留言交流!我是欧阳瑞,极客之路,永无止境!


技术栈:RabbitMQ · 消息队列 · 事件驱动

相关推荐
zhuangzhao11921 小时前
第一性原理大模型课程 · 第 21 课:从 Prompt 到 Agent:四件套、错误累积与 ReAct 手算
大模型·react·ai agent·错误累积·大模型课程
liwulin05061 天前
【OLLAMA】LangGrahp调用LLM WIKI
react·ollama·llm wiki
澹锦汐2 天前
纯前端秋日银杏与枫叶落叶色板智能聚类器:基于 K-Means 色彩量化与直方图自动配方提取
前端·人工智能·ai·语言模型·vue·react·k-means
Bczheng12 天前
五十六.网络(6)--广播tx测试
区块链
Java码农也是农3 天前
React useEffect 详解:依赖、清理、重复执行与请求竞态
react·前端开发·hooks·useeffect·请求竞态
笑容掩饰我的失落7 天前
区块链从小白到精通(十):合约安全与上线——重入攻击、Gas 优化与最佳实践
安全·区块链
OxYGC8 天前
[Web3] 智能合约 04: 高级开发实战与 OpenZeppelin
web3·区块链·智能合约
笑容掩饰我的失落8 天前
区块链从小白到精通(七):Solidity 语法精讲——数据类型、函数、修饰器与事件
算法·区块链·php·智能合约·哈希算法
OxYGC8 天前
[Web3] 智能合约 03: 函数/事件/继承/接口/异常处理
web3·区块链·智能合约
笑容掩饰我的失落9 天前
区块链从小白到精通(八):从零实现一个标准 ERC-20 代币(完整可运行代码)
算法·区块链·php·智能合约·哈希算法