当前位置: 首页 > news >正文

RabbitMQ 入门教程

概述

RabbitMQ 是一个开源的消息代理和队列服务器,实现了 AMQP 0-9-1 标准。它可以在完全不同的应用程序之间传递消息。本教程将带你从零开始学习如何使用 RabbitMQ。

环境准备

1. 安装 RabbitMQ

- 在命令行中运行 `sudo apt-get install rabbitmq-server` (Ubuntu) 或者通过官方文档获取其他系统的安装指南。

2. 启动服务

- 运行 `sudo service rabbitmq-server start`。

3. 安装客户端库

- 对于 Python: `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()

```

第二步:工作队列

生产者

```python

import pika

import sys

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

channel = connection.channel()

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

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

channel.basic_publish(

exchange='',

routing_key='task_queue',

body=message,

properties=pika.BasicProperties(

delivery_mode=2, # make message persistent

))

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

connection.close()

```

消费者

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

```

第三步:发布/订阅

发布端

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

```

接收端 1

```python

import pika

import uuid

def on_message(channel, method, props, 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)

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

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

channel.start_consuming()

```

接收端 2

```python

import pika

import uuid

def on_message(channel, method, props, 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)

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

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

channel.start_consuming()

```

第四步:路由模式

发送端

```python

import pika

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

channel = connection.channel()

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)

print(" [x] Sent %r:%r" % (severity, message))

connection.close()

```

接收端

```python

import pika

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

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

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

channel = connection.channel()

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

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

queue_name = result.method.queue

severities = ['error', 'warning']

for severity in severities:

channel.queue_bind(

exchange='direct_logs', queue=queue_name, routing_key=severity)

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

相关文章:

  • 在模板中使用 Django 会话
  • 828华为云征文|华为云Flexus云服务器X实例部署Cockpit服务
  • 【Django-Minio-Storage 使用教程】
  • RabbitMQ核心架构
  • spring boot 项目 prometheus 自定义指标收集区分应用环境集群实例ip,使用 grafana 查询--方法耗时分位数指标
  • RK3588平台开发系列讲解(显示篇)图像的宽高和跨距
  • Linux之grafana+onealert报警
  • 回调函数的概念及其在异步编程中的应用
  • React基础教程(09):react的属性介绍(props)
  • pr瘦脸怎么操作?
  • Python sys 库的应用实例
  • 达梦数据库的系统视图v$sysstat
  • 人工智能造福公众:未来一片光明
  • 学习计算机网络
  • Seata 分布式事务控制
  • Axure设计效率提升:实战策略与技巧
  • ChatGPT 3.5/4.0使用手册:解锁人工智能的无限潜能
  • 前端面试笔记(三)--(基础知识篇sz)
  • 基于RK3568平台移植ffmpeg3.4.5及ffmpeg验证
  • AMP网站的SEO 关于“备用网页”应该如何处理?
  • 上海灵活就业人员公积金新政有哪些“创新点”?
  • “五一”假期全国口岸日均出入境人员将达215万人次
  • 在差异中建共鸣,《20世纪美国文学思想研究》丛书出版
  • 多地征集农村假冒伪劣食品违法线索,全链条整治“三无”产品
  • 比亚迪一季度日赚亿元,净利润同比翻倍至91.55亿元
  • “2025上海西九文化周”启动,香港顶尖文艺6月齐聚申城