RabbitMQ 入门教程

介绍

RabbitMQ 是一个开源的消息代理和队列服务器,实现高级消息队列协议 (AMQP)。它能够将消息在发送者和多个接收者之间进行路由。

安装与配置

安装

Ubuntu

```bash

sudo apt-get update

sudo apt-get install rabbitmq-server

```

macOS (通过 Homebrew)

```bash

brew install rabbitmq

```

启动服务

```bash

rabbitmq-server

```

配置

默认情况下,RabbitMQ 使用端口 `5672`。可以通过编辑 `/etc/rabbitmq/rabbitmq.config` 进行配置。

基础概念

- Exchange: 接收并转发消息到队列。

- Queue: 存储消息直到它们被消费。

- Binding: 交换机和队列之间的连接规则。

- Message: 发送的数据单元。

- Routing Key: 绑定中使用的字符串,帮助交换机将消息路由到正确的队列。

示例代码

Python 环境准备

```bash

pip install pika

```

生产者

```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()

```

工作模式

发布/订阅 (Fanout)

- Exchange Type: `fanout`

- Behavior: 广播所有绑定的队列。

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

message = "Info: Hello World!"

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

```

```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(" [x] %r" % body)

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()

```

路由 (Direct)

- Exchange Type: `direct`

- Behavior: 根据路由键发送消息到匹配的队列。

```python

生产者

channel.exchange_declare(exchange='direct_logs', exchange_type='direct')

severity = sys.argv[1] if len(sys.argv) > 1 else 'info'

message = ' '.join(sys.argv[2:]) or 'Hello World!'

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

```

```python

消费者

channel.exchange_declare(exchange='direct_logs', exchange_type='direct')

severities = ['error', 'warning']

for severity in severities:

queue = channel.queue_declare(queue='', exclusive=True)

queue_name = queue.method.queue

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

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

print(" [x] %r:%r" % (method.routing_key, body))

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

```

主题 (Topic)

- Exchange Type: `topic`

- Behavior: 基于模式匹配发送消息到队列。

```python

生产者

channel.exchange_declare(exchange='topic_logs', exchange_type='topic')

routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info'

message = ' '.join(sys.argv[2:]) or 'Hello World!'

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

```

```python

消费者

channel.exchange_declare(exchange='topic_logs', exchange_type='topic')

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

queue_name = result.method.queue

binding_keys = ['*.orange.*', '*.black.*']

for binding_key in binding_keys:

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

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

print(" [x] %r:%r" % (method.routing_key, body))

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

```

高级特性

持久化

```python

生产者

channel.queue_declare(queue='task_queue', durable=True)

message = 'Hello World!'

channel.basic_publish(exchange='',

routing_key='task_queue',

body=message,

properties=pika.BasicProperties(

delivery_mode = 2, # make message persistent

))

```

事务

```python

生产者

channel.confirm_delivery()

try:

channel.basic_publish(exchange='',

routing_key='hello',

body='Hello World!')

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

except Exception as e:

channel.rollback()

print(f"Failed to publish message: {e}")

else:

channel.commit()

```

手动确认

```python

消费者

channel.basic_consume(queue='hello',

on_message_callback=callback)

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

channel.start_consuming()

```

死信队列

```python

生产者

channel.queue_declare(queue='task_queue', durable=True)

message = 'Hello World!'

channel.basic_publish(exchange='',

routing_key='task_queue',

body=message,

properties=pika.BasicProperties(

expiration='60000' # expire after 1 minute

))

```

```python

消费者

channel.queue_declare(queue='dead_letter_queue')

channel.queue_declare(queue='task_queue', arguments={

'x-message-ttl': 60000, # Message expires after 1 minute

'x-dead-letter-exchange': '',

'x-dead-letter-routing-key': 'dead_letter_queue'

})

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值