一、简单的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. 分布式的几件小事(五)dubbo的spi思想是什么

    1.什么是SPI机制 SPI 全称为 Service Provider Interface,是一种服务发现机制. SPI 的本质是将接口实现类的全限定名配置在文件中,并由服务加载器读取配置文件,加载实 ...

  2. dedecms 列表 用分页标签 判断 当第一页则显示,第二页以上不显示 土办法!

    arc.listview.class.php function GetPageListST($list_len,$listitem="index,end,pre,next,pageno,sp ...

  3. CUDA升级后

    打开工程文件.vcxproj,找到 <Import Project="$(VCTargetsPath)\BuildCustomizations\CUDA 10.0.props" ...

  4. tensorflow各版本下载地址

    https://pypi.org/project/tensorflow-gpu/1.13.0/#files 把13改对你想要的版本

  5. [易学易懂系列|rustlang语言|零基础|快速入门|(21)|智能指针]

    [易学易懂系列|rustlang语言|零基础|快速入门|(21)|智能指针] 实用知识 智能指针 我们今天来讲讲Rust中的智能指针. 什么是指针? 在Rust,指针(普通指针),就是保存内存地址的值 ...

  6. 【BZOJ4596】【Luogu P4336】 [SHOI2016]黑暗前的幻想乡 矩阵树定理,容斥

    同样是矩阵树定理的裸题.但是要解决它需要能够想到容斥才可以. \(20\)以内的数据范围一定要试试容斥的想法. #include <bits/stdc++.h> using namespa ...

  7. beautifulsoup4 用法一二

    声明一个beautifulsoup4对象 bs = ( url,//路由 html_parser,//解析html代码 encoding//编码)//另一种请求解析方法 import requests ...

  8. 02-01 Django之路由层

    Django之路由层 一 路由的作用 路由即请求地址与视图函数的映射关系,如果把网站比喻为一本书,那路由就好比是这本书的目录,在Django中路由默认配置在urls.py中,如下图: 二 简单的路由配 ...

  9. MySQL内联和外联查询

    内连: 内连接是通过在查询中设置连接条件的方式,来移除查询结果集中某些数据行后的交叉连接.简单来说,就是利用条件表达式来消除交叉连接的某些数据行. 在MySQL FROM 子句中使用关键字 INNER ...

  10. JZOJ5358【NOIP2017提高A组模拟9.12】BBQ

    题目 分析 发现,\(C_{ai+aj+bi+bj}^{ai+aj}\),其实就等于从(0,0)走最短路到(ai+aj,bi+bj). 我们可以想办法将i.j分开,从(0,0)走最短路到(ai+aj, ...