Python RabbitMQ

需要安装erlang和RabbitMQ

1. 一对一

producer:

1import pika 2 3connection = pika.BlockingConnection(pika.ConnectionParameters( 4 'localhost')) 5channel = connection.channel() 6 7# 声明queue 8channel.queue_declare(queue='hello',durable=True) # durable=True,将队列持久化,哪怕 RabbitMQ服务重启,此队列依然存在 9 10# RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange. 11channel.basic_publish(exchange='', 12 routing_key='hello', 13 body='Hello World!', 14 properties=pika.BasicProperties(delivery_mode=2) # 将队列中的消息也持久化 15 ) 16print(" [x] Sent 'Hello World!'") 17connection.close()

consumer:

1import pika 2import time 3 4connection = pika.BlockingConnection(pika.ConnectionParameters( 5 'localhost')) 6channel = connection.channel() 7 8# 为什么又声明一遍这个队列(生产者已经声明过了),因为如果消费者先运行起来,此时又没有声明的话,会报错, 9# 所以在这里重新声明一遍,防止出错罢了。 10channel.queue_declare(queue='hello',durable=True) # durable=True,将队列持久化,哪怕 RabbitMQ服务重启,此队列依然存在 11 12 13def callback(ch, method, properties, body): 14 print('-->',ch,method,properties) 15 # time.sleep(30) 16 print(" [x] Received %r" % body) 17 ch.basic_ack(delivery_tag=method.delivery_tag) # 手动应答,只有消费者确认了,才会从队列删除 18 19channel.basic_qos(prefetch_count=1) # 只要一个消费者的队列中还有1个消息,就不继续推送给这个消费者 20 21channel.basic_consume('hello', 22 callback, 23 # auto_ack=True # 自动应答,消费者一收到消息,消息就自动从队列中删除,如果消费者没有处理完此消息,也会删除。 24 ) 25 26print(' [*] Waiting for messages. To exit press CTRL+C') 27channel.start_consuming()

2. 一对多广播:fanout

producer:

1import pika 2import sys 3 4connection = pika.BlockingConnection(pika.ConnectionParameters( 5 host='localhost')) 6channel = connection.channel() 7 8channel.exchange_declare(exchange='logs', # 随意声明一个叫 logs 的 exchange 9 exchange_type='fanout') # 类型用fanout,可以对所有绑定此exchange的channel进行广播 10 11message = "info: Hello World!" 12channel.basic_publish(exchange='logs', 13 routing_key='', # 不设定routing_key,就是对所有绑定此exchange的channel进行推送消息 14 body=message) 15print(" [x] Sent %r" % message) 16connection.close()

consumer:

1import pika 2 3connection = pika.BlockingConnection(pika.ConnectionParameters( 4 host='localhost')) 5channel = connection.channel() 6 7channel.exchange_declare(exchange='logs', 8 exchange_type='fanout') 9 10result = channel.queue_declare('',exclusive=True) # queue名字为空,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除 11queue_name = result.method.queue 12 13channel.queue_bind(exchange='logs', # 绑定名为logs的exchange 14 queue=queue_name) 15 16print(' [*] Waiting for logs. To exit press CTRL+C') 17 18def callback(ch, method, properties, body): 19 print(" [x] %r" % body) 20 21channel.basic_consume(queue_name, 22 callback, 23 auto_ack=True) 24 25channel.start_consuming()

3. 有选择的接受消息:direct

producer:

1import pika 2import sys 3 4connection = pika.BlockingConnection(pika.ConnectionParameters( 5 host='localhost')) 6channel = connection.channel() 7 8channel.exchange_declare(exchange='direct_logs', 9 exchange_type='direct') 10 11severity = sys.argv[1] if len(sys.argv) > 1 else 'info' 12message = ' '.join(sys.argv[2:]) or 'Hello World!' 13channel.basic_publish(exchange='direct_logs', 14 routing_key=severity, 15 body=message) 16print(" [x] Sent %r:%r" % (severity, message)) 17connection.close()

consumer:

1import pika 2import sys 3 4connection = pika.BlockingConnection(pika.ConnectionParameters( 5 host='localhost')) 6channel = connection.channel() 7 8channel.exchange_declare(exchange='direct_logs', # 声明一个exchange的名字和类型 9 exchange_type='direct') 10 11result = channel.queue_declare('',exclusive=True)# 随机生成一个唯一的queue 12queue_name = result.method.queue 13 14severities = sys.argv[1:] # 从命令行获取参数 15if not severities: 16 # sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0]) 17 # sys.exit(1) 18 severities = ['info'] 19 20 21for severity in severities: 22 channel.queue_bind(exchange='direct_logs', # 绑定到direct_logs上 23 queue=queue_name, 24 routing_key=severity) # 指向相应的生产者上 25 26print(' [*] Waiting for logs. To exit press CTRL+C') 27 28 29def callback(ch, method, properties, body): 30 print(" [x] %r:%r" % (method.routing_key, body)) 31 32channel.basic_consume(queue_name, 33 callback, 34 auto_ack=True) 35channel.start_consuming()

3. 过滤特殊字段的消息:topic

producer:

1import pika 2import sys 3 4connection = pika.BlockingConnection(pika.ConnectionParameters( 5 host='localhost')) 6channel = connection.channel() 7 8channel.exchange_declare(exchange='topic_logs', 9 exchange_type='topic') 10 11routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info' 12message = ' '.join(sys.argv[2:]) or 'Hello World!' 13channel.basic_publish(exchange='topic_logs', 14 routing_key=routing_key, 15 body=message) 16print(" [x] Sent %r:%r" % (routing_key, message)) 17connection.close()

consumer:

1import pika 2import sys 3 4connection = pika.BlockingConnection(pika.ConnectionParameters( 5 host='localhost')) 6channel = connection.channel() 7 8channel.exchange_declare(exchange='topic_logs', 9 exchange_type='topic') 10 11result = channel.queue_declare('',exclusive=True) 12queue_name = result.method.queue 13 14binding_keys = sys.argv[1:] 15if not binding_keys: 16 # sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0]) 17 # sys.exit(1) 18 binding_keys = ['anonymous.*'] # *代表匹配任意字符,# 代表匹配所有:binding_keys=['#','*.abc','aaa.*'] 19 20for binding_key in binding_keys: 21 channel.queue_bind(exchange='topic_logs', 22 queue=queue_name, 23 routing_key=binding_key) 24 25print(' [*] Waiting for logs. To exit press CTRL+C') 26 27 28def callback(ch, method, properties, body): 29 print(" [x] %r:%r" % (method.routing_key, body)) 30 31 32channel.basic_consume(queue_name, 33 callback, 34 auto_ack=True) 35 36channel.start_consuming()
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )