【进阶】消息队列简介:RabbitMQ与Kafka
发布时间: 2024-06-25 18:38:49 阅读量: 70 订阅数: 107
消息队列RabbitMQ介绍
5星 · 资源好评率100%
![【进阶】消息队列简介:RabbitMQ与Kafka](https://sipodsoftware.com/wp-content/uploads/2023/04/2.jpg)
# 2.1.1 安装RabbitMQ
**Linux系统安装**
```bash
sudo apt-get update
sudo apt-get install rabbitmq-server
```
**Windows系统安装**
1. 下载RabbitMQ安装包:https://www.rabbitmq.com/download.html
2. 双击安装包,按照提示进行安装
**安装验证**
安装完成后,可以通过以下命令验证RabbitMQ是否安装成功:
```bash
rabbitmqctl status
```
输出结果如下表示安装成功:
```
Status of RabbitMQ node 'rabbit@hostname' ...
```
# 2. RabbitMQ实践应用
### 2.1 RabbitMQ的安装和配置
#### 2.1.1 安装RabbitMQ
**Linux系统安装**
```bash
# 添加RabbitMQ源
sudo apt-get update
sudo apt-get install apt-transport-https
wget -O /etc/apt/trusted.gpg.d/rabbitmq-release-signing-key.asc https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x6B73A36F
sudo sh -c 'echo "deb https://dl.bintray.com/rabbitmq-erlang/debian $(lsb_release -cs) main" > /etc/apt/sources.list.d/rabbitmq.list'
# 安装RabbitMQ
sudo apt-get update
sudo apt-get install rabbitmq-server
```
**Windows系统安装**
1. 下载RabbitMQ安装包:https://www.rabbitmq.com/download.html
2. 双击安装包,按照提示安装即可。
#### 2.1.2 配置RabbitMQ
**修改默认端口**
```bash
# 编辑配置文件
sudo nano /etc/rabbitmq/rabbitmq-env.conf
# 修改端口号
RABBITMQ_NODE_PORT=5672
```
**启用管理插件**
```bash
# 编辑配置文件
sudo nano /etc/rabbitmq/rabbitmq.config
# 启用管理插件
[management]
enabled = true
```
**重启RabbitMQ**
```bash
sudo service rabbitmq-server restart
```
### 2.2 RabbitMQ的消息发送和接收
#### 2.2.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!')
```
**消费者接收消息**
```python
import pika
# 建立连接
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 创建队列
channel.queue_declare(queue='hello')
# 定义回调函数
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
# 消费消息
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
# 进入循环等待消息
channel.start_consuming()
```
#### 2.2.2 消息的路由和交换机
**Exchange类型**
| 类型 | 描述 |
|---|---|
| Direct | 根据routing key直接将消息路由到特定队列 |
| Fanout | 将消息广播到所有绑定的队列 |
| Topic | 根据routing key中的模式将消息路由到匹配的队列 |
**绑定队列和交换机**
```bash
# 绑定队列到Direct交换机
rabbitmqadmin declare exchange name=my-exchange type=direct
rabbitmqadmin declare queue name=my-queue
rabbitmqadmin bind queue name=my-queue exchange=my-exchange routing_key=my-routing-key
```
#### 2.2.3 消息的持久化和可靠性
**消息持久化**
* 将消息存储在磁盘上,即
0
0