一、简单的RabbitMQ示例

  • 生产者
# Author:Li Dongfei
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
) #建立一个连接
channel = connection.channel() #声明一个管道
channel.queue_declare(queue='hello') #生成一个queue
channel.basic_publish(exchange='',
routing_key='hello', #queue名字
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
  • 消费者
# Author:Li Dongfei
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print("-->", ch, method, properties)
print(" [x] Received %r" %body)
channel.basic_consume(callback, #开始消费消息,如果收到消息就调用callback函数来处理消息
queue='hello',
no_ack=True
)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始收消息

二、RabbitMQ命令行工具

C:\>cd C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.12\sbin
C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.12\sbin>rabbitmqctl.bat list_queues #列出当前的queue

三、rabbitmq持久化

  • 队列持久化
channel.queue_declare(queue='hello', durable=True)  #durable=True声明队列持久化
  • 消息持久化
channel.basic_publish(exchange='',
routing_key='hello', #queue名字
body='Hello World!',
properties=pika.BasicProperties(
delivery_mode=2 #消息持久化
))

四、消息调度

  • 在消费者中定义
channel.basic_qos(prefetch_count=1)  #只要当前有一条消息在处理则不要给我发消息

五、广播模式

  • fanout:所有bind到此exchange的queue都可以接受消息
  • 订阅/发布

    生成者
# Author:Li Dongfei
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()

消费者

# Author:Li Dongfei
import pika connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
channel = connection.channel()
channel.exchange_declare(exchange='logs',
exchange_type='fanout') result = channel.queue_declare(exclusive=True) #exclusive 唯一的
queue_name = result.method.queue channel.queue_bind(exchange='logs',
queue=queue_name) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body):
print(" [x] %r" %body) channel.basic_consume(callback,
queue=queue_name,
no_ack=True) channel.start_consuming()
  • direct:通过routingKey和exchange决定的哪个唯一的queue可以接受消息

    生产者
# Author:Li Dongfei

import pika, sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'
))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs',
exchange_type='direct') serverity = 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=serverity,
body=message)
print(" [x] Sent %r:%r" %(serverity, message))
connection.close()

消费者

# Author:Li Dongfei

import pika, sys

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs',
exchange_type='direct') result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue serverities = sys.argv[1:]
if not serverities:
sys.stderr.write("Usage: %s [info] [warning] [error]\n" %sys.argv[0])
sys.exit(1) for serverity in serverities:
channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key=serverity) print(' [*] Wating for logs. To exit press CTRL+C') def callback(ch, method, properties, body):
print(" [x] %r:%r" %(method.routing_key, body)) channel.basic_consume(callback,
queue=queue_name,
no_ack=True) channel.start_consuming()
  • topic:所有符合routingKey的routingKey所bind的queue可以接受消息

六、rabbitMQ rpc

  • client
# Author:Li Dongfei

import pika, uuid

class FibonacciTpcClient(object):
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'
)) self.channel = self.connection.channel() result = self.channel.queue_declare(exclusive=True)
self.callback_queue = result.method.queue self.channel.basic_consume(self.on_response, no_ack=True,
queue=self.callback_queue) 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 = FibonacciTpcClient() print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call(30)
print(" [.] Got %r" %response)
  • server
# Author:Li Dongfei

import pika, time

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'
)) channel = connection.channel()
channel.queue_declare(queue='rpc_queue') def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2) def on_request(ch, method, props, body):
n = int(body)
print(" [.] fib(%s)" %n)
response = 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) channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_request, queue='rpc_queue') print(" [x] Awatiing RPC requests")
channel.start_consuming()

190707Python-RabbitMQ的更多相关文章

  1. 消息队列——RabbitMQ学习笔记

    消息队列--RabbitMQ学习笔记 1. 写在前面 昨天简单学习了一个消息队列项目--RabbitMQ,今天趁热打铁,将学到的东西记录下来. 学习的资料主要是官网给出的6个基本的消息发送/接收模型, ...

  2. RabbitMq应用二

    在应用一中,基本的消息队列使用已经完成了,在实际项目中,一定会出现各种各样的需求和问题,rabbitmq内置的很多强大机制和功能会帮助我们解决很多的问题,下面就一个一个的一起学习一下. 消息响应机制 ...

  3. 如何优雅的使用RabbitMQ

    RabbitMQ无疑是目前最流行的消息队列之一,对各种语言环境的支持也很丰富,作为一个.NET developer有必要学习和了解这一工具.消息队列的使用场景大概有3种: 1.系统集成,分布式系统的设 ...

  4. RabbitMq应用一的补充(RabbitMQ的应用场景)

    直接进入正题. 一.异步处理 场景:发送手机验证码,邮件 传统古老处理方式如下图 这个流程,全部在主线程完成,注册->入库->发送邮件->发送短信,由于都在主线程,所以要等待每一步完 ...

  5. RabbitMq应用一

    RabbitMq应用一 RabbitMQ的具体概念,百度百科一下,我这里说一下我的理解,如果有少或者不对的地方,欢迎纠正和补充. 一个项目架构,小的时候,一般都是传统的单一网站系统,或者项目,三层架构 ...

  6. 缓存、队列(Memcached、redis、RabbitMQ)

    本章内容: Memcached 简介.安装.使用 Python 操作 Memcached 天生支持集群 redis 简介.安装.使用.实例 Python 操作 Redis String.Hash.Li ...

  7. 消息队列性能对比——ActiveMQ、RabbitMQ与ZeroMQ(译文)

    Dissecting Message Queues 概述: 我花了一些时间解剖各种库执行分布式消息.在这个分析中,我看了几个不同的方面,包括API特性,易于部署和维护,以及性能质量..消息队列已经被分 ...

  8. windows下 安装 rabbitMQ 及操作常用命令

    rabbitMQ是一个在AMQP协议标准基础上完整的,可服用的企业消息系统.它遵循Mozilla Public License开源协议,采用 Erlang 实现的工业级的消息队列(MQ)服务器,Rab ...

  9. RabbitMQ + PHP (三)案例演示

    今天用一个简单的案例来实现 RabbitMQ + PHP 这个消息队列的运行机制. 主要分为两个部分: 第一:发送者(publisher) 第二:消费者(consumer) (一)生产者 (创建一个r ...

  10. RabbitMQ + PHP (二)AMQP拓展安装

    上篇说到了 RabbitMQ 的安装. 这次要在讲案例之前,需要安装PHP的AMQP扩展.不然可能会报以下两个错误. 1.Fatal error: Class 'AMQPConnection' not ...

随机推荐

  1. jquery 滚动事件-记录自己常用的

    1.h5端页面滑动至第3屏及以后才出现置顶按钮 $(document).scroll(function() { var scroH = $(document).scrollTop(); //滚动高度 ...

  2. 使用sublimeserver启动本地服务器进行调试

    最近在做前后端分离的项目,访问后台接口的时候会产生跨域问题,修改了相关配置解决了跨域问题,但是配置中只对开发环境进行了设置,没有设置生产环境,为了验证生产环境确实无法访问后台接口遂npm run bu ...

  3. 从命令行运行postman脚本

    为什么要在命令行中运行 可以在无UI界面的服务器上运行 可以在持续集成系统上运行 运行准备 导出collection 安装nodejs和npm(或cnpm) 安装Newman 运行及生成测试报告支持4 ...

  4. 渗透神器CobaltStrike 3.1.2 去后门破解版 & Windows版TeamServer【转】

    转自我八师傅博客 CS简介 Cobalt Strike(简称CS)是全球黑客公认一款非常优秀的渗透测试神器,以metasploit为基础的GUI的框架式渗透工具,集成了传统远控功能(远程桌面VNC.键 ...

  5. mysql数据库备份与恢复命令

    mysqldump -h主机名  -P端口 -u用户名 -p密码 [--databases] 数据库名(可以是多个,用空格分割) > 文件名.sql 备份MySQL数据库的命令(备份脚本中不包含 ...

  6. Delphi SpeedButton组件

  7. jQuery获取兄弟标签的文本

    // 一个div里面有一个span标签和多个button标签,每个button标签都有id,span标签没有id,通过点击其中一个button标签,来获取到span标签的text function ( ...

  8. kubernetes创建资源的两种方式

    一.创建方式分类: 命令 vs 配置文件 Kubernetes 支持两种方式创建资源: 1.用 kubectl 命令行的方式直接创建,比如: kubectl run httpd-app --image ...

  9. java8学习之收集器枚举特性深度解析与并行流原理

    首先先来找出上一次[http://www.cnblogs.com/webor2006/p/8353314.html]在最后举的那个并行流报错的问题,如下: 在来查找出上面异常的原因之前,当然得要一点点 ...

  10. Oracle 导入dump

    1. 准备好.dmp文件