RabbitMQ 入门教程

admin2024-09-11  23

介绍

RabbitMQ 是一个开源的消息代理和队列服务器,实现了高级消息队列协议 (AMQP)。它能够在生产者和消费者之间传递消息,并且能够保证消息的可靠传输。

安装与配置

安装 RabbitMQ

1. Ubuntu:

```bash

sudo apt update

sudo apt install rabbitmq-server

```

2. MacOS (Homebrew):

```bash

brew install rabbitmq

```

3. Windows:

- 下载安装包并运行安装向导。

启动与停止服务

- 启动:

```bash

sudo service rabbitmq-server start

```

- 停止:

```bash

sudo service rabbitmq-server stop

```

配置管理插件

```bash

sudo rabbitmq-plugins enable rabbitmq_management

```

访问管理界面

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

- 默认用户名和密码均为 `guest`。

发布/订阅模式

发布/订阅模式允许消息发送给多个接收者。

创建发布者 (Publisher)

```python

import pika

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

channel = connection.channel()

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

message = "Hello, world!"

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

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

connection.close()

```

创建订阅者 (Subscriber)

```python

import pika

import sys

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

print(" [x] Received %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)

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

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

channel.start_consuming()

```

工作队列模式

工作队列模式将任务分布到多个工作者节点。

创建生产者 (Producer)

```python

import pika

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

channel = connection.channel()

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

message = "A new task"

channel.basic_publish(

exchange='',

routing_key='task_queue',

body=message,

properties=pika.BasicProperties(

delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE

))

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

connection.close()

```

创建消费者 (Consumer)

```python

import pika

import time

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

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

time.sleep(body.count(b'.'))

print(" [x] Done")

ch.basic_ack(delivery_tag=method.delivery_tag)

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

channel = connection.channel()

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

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

channel.basic_qos(prefetch_count=1)

channel.basic_consume(queue='task_queue', on_message_callback=callback)

channel.start_consuming()

```

RPC 模式

RPC (Remote Procedure Call) 模式使得客户端能够通过网络远程调用一个函数。

创建服务端 (Server)

```python

import pika

import fib

def on_request(ch, method, props, body):

n = int(body)

print(" [.] fib(%s)" % n)

response = fib.fib(n)

ch.basic_publish(exchange='',

routing_key=props.reply_to,

properties=pika.BasicProperties(correlation_id=props.correlation_id),

body=str(response))

ch.basic_ack(delivery_tag=method.delivery_tag)

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

channel = connection.channel()

channel.queue_declare(queue='rpc_queue')

channel.basic_qos(prefetch_count=1)

channel.basic_consume(queue='rpc_queue', on_message_callback=on_request)

print(" [x] Awaiting RPC requests")

channel.start_consuming()

```

创建客户端 (Client)

```python

import pika

import uuid

import fib

class FibonacciRpcClient(object):

def __init__(self):

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

self.channel = self.connection.channel()

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

self.callback_queue = result.method.queue

self.channel.basic_consume(

queue=self.callback_queue,

on_message_callback=self.on_response,

auto_ack=True)

def on_response(self, ch, method, props, body):

if self.corr_id == props.correlation_id:

self.response = body

def call(self, n):

self.response = None

self.corr_id = str(uuid.uuid4())

self.channel.basic_publish(

exchange='',

routing_key='rpc_queue',

properties=pika.BasicProperties(

reply_to=self.callback_queue,

correlation_id=self.corr_id,

),

body=str(n))

while self.response is None:

self.connection.process_data_events()

return int(self.response)

fibonacci_rpc = FibonacciRpcClient()

print(" [x] Requesting fib(30)")

response = fibonacci_rpc.call(30)

print(" [.] Got %r" % response)

thon 客户端](https://pika.readthedocs.io/en/stable/)

```

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!