RabbitMQ 入门教程

介绍

RabbitMQ 是一个消息中间件平台,它实现了 AMQP (Advanced Message Queuing Protocol) 协议。RabbitMQ 可以帮助应用程序解耦、增加弹性并且提高性能。

安装与配置

1. 安装 RabbitMQ

Ubuntu:

```bash

sudo apt-get update

sudo apt-get install rabbitmq-server

```

Windows:

- 下载安装包: https://www.rabbitmq.com/download.html

- 运行安装程序并按照提示完成安装。

2. 启动服务

```bash

sudo service rabbitmq-server start

```

3. 配置管理插件

```bash

sudo rabbitmq-plugins enable rabbitmq_management

```

4. 访问管理界面

- 打开浏览器访问: http://localhost:15672/

- 用户名/密码: guest/guest

快速开始

创建生产者

```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!')

print(" [x] Sent 'Hello World!'")

connection.close()

```

创建消费者

```python

import pika

def callback(ch, method, properties, body):

print(" [x] Received %r" % body)

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

channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_consume(queue='hello',

on_message_callback=callback,

auto_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')

channel.start_consuming()

```

深入理解消息队列

基本概念

- Exchange: 负责接收和分发消息。

- Queue: 存储消息的地方。

- Binding: Exchange 和 Queue 之间的连接。

- Routing Key: 用于路由消息的键。

工作模式

1. 简单模式 (Simple)

- 生产者直接将消息发送到队列。

2. 工作队列模式 (Work Queues)

- 通过负载均衡实现任务分发。

3. 发布/订阅模式 (Publish/Subscribe)

- 多个消费者订阅同一 Exchange。

4. 路由模式 (Routing)

- 根据 Routing Key 分发消息。

5. 主题模式 (Topics)

- 支持模糊匹配的 Routing Key。

示例代码

发布/订阅模式

生产者

```python

import pika

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

channel = connection.channel()

channel.exchange_declare(exchange='logs', exchange_type='fanout')

message = "Info: Hello World!"

channel.basic_publish(exchange='logs', routing_key='', body=message)

print(" [x] Sent %r" % message)

connection.close()

```

消费者

```python

import pika

def callback(ch, method, properties, body):

print(" [x] %r" % body)

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

channel = connection.channel()

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)

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

print(' [*] Waiting for logs. To exit press CTRL+C')

channel.start_consuming()

```

总结

RabbitMQ 提供了灵活的消息传递机制,适用于多种应用场景。通过上述示例,你已经了解了如何使用 Python 与 RabbitMQ 交互。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值