Python3之RabbitMQ
Python3之RabbitMQ
简介
RabbitMQ安装
- Linux安装,环境centos7
1
2
3
4
5
6
7
8
9
|
安装配置epel源 # rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm 安装erlang # yum -y install erlang 安装RabbitMQ # yum -y install rabbitmq-serverservice rabbitmq-server start/stop 注意:需要关闭防火墙和selinux # systemctl stop firewalld.service # setenforce 0 |
- Ubuntu 安装
1
2
3
4
5
6
7
8
|
# apt-get install build-essential # apt-get install libncurses5-dev # apt-get install libssl-dev # apt-get install erlang 编辑 / etc / apt / sources. list 加入 deb http: / / www.rabbitmq.com / debian / testing main # wget -O- https://www.rabbitmq.com/rabbitmq-release-signing-key.asc | apt-key add - # apt-get update # apt-get install rabbitmq-server |
- windows 安装
1
2
3
4
5
6
7
8
|
首先是到ERLang官网去下载ERlang 地址:http: / / www.erlang.org / download.html 然后安装ERLang。 然后设置ERLang的环境变量。 在环境变量中加入 ERL_HOME = erlang安装目录 在path中添加 % ERL_HOME % \ bin 然后从http: / / www.rabbitmq.com / releases / rabbitmq - server / v3. 1.5 / rabbitmq - server - 3.1 . 5.exe 下载rabbitmq - server 并安装。 然后从 开始菜单中找到 rabbitmq - start 打开 此刻rabbitmq - server就启动了 |
- 安装Python API
1
2
3
|
pip install pika or easy_install pika |
基于queue实现生产消费者模型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#!/usr/bin/env python3 #coding:utf8 import queue import threading message = queue.Queue( 10 ) def producer(i): '''厨师,生产包子放入队列''' while True : message.put(i) print ( "%s放入队列%s" % (threading.current_thread().name, i)) def consumer(i): '''消费者,从队列中取包子吃''' while True : msg = message.get() print ( "%s从队列总取出%s" % (threading.current_thread().name, msg)) if __name__ = = '__main__' : for i in range ( 12 ): # 厨师的线程包子 t = threading.Thread(target = producer, args = (i,)) t.start() for i in range ( 10 ): # 消费者的线程吃包子 t = threading.Thread(target = consumer, args = (i,)) t.start() |
RabbitMQ 使用
- 生产者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#!/usr/bin/env python 3 import pika ######### 生产者 ######### #链接rabbit服务器(localhost是本机,如果是其他服务器请修改为ip地址) connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) #创建频道 channel = connection.channel() #创建一个队列名叫test channel.queue_declare(queue = 'test' ) # channel.basic_publish向队列中发送信息 # exchange -- 它使我们能够确切地指定消息应该到哪个队列去。 # routing_key 指定向哪个队列中发送消息 # body是要插入的内容, 字符串格式 while True : # 循环向队列中发送信息,quit退出程序 inp = input ( ">>>" ).strip() if inp = = 'quit' : break channel.basic_publish(exchange = '', routing_key = 'test' , body = inp) print ( "生产者向队列发送信息%s" % inp) #缓冲区已经flush而且消息已经确认发送到了RabbitMQ中,关闭链接 connection.close() # 输出结果 >>>python 生产者向队列发送信息python >>>quit |
- 消费者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#!/usr/bin/env python 3 import pika ######### 消费者 ######### # 链接rabbit connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) # 创建频道 channel = connection.channel() # 如果生产者没有运行创建队列,那么消费者也许就找不到队列了。为了避免这个问题,所有消费者也创建这个队列,如果队列已经存在,则这条无效 channel.queue_declare(queue = 'test' ) #接收消息需要使用callback这个函数来接收,他会被pika库来调用,接受到的数据都是字节类型的 def callback(ch, method, properties, body): """ ch : 代表 channel method :队列名 properties : 连接rabbitmq时设置的属性 body : 从队列中取到的内容,获取到的数据时字节类型 """ print ( " [x] Received %r" % body) # channel.basic_consume 表示从队列中取数据,如果拿到数据 那么将执行callback函数,callback是回调函数 # no_ack=True 表示消费完这个消息以后不主动把完成状态通知rabbitmq channel.basic_consume(callback, queue = 'test' , no_ack = True ) print ( ' [*] 等待信息. To exit press CTRL+C' ) #永远循环等待数据处理和callback处理的数据,start_consuming方法会阻塞循环执行 channel.start_consuming() # 输出结果,一直等待处理队列中的消息,不知终止,除非人为ctrl+c [ * ]等待消息,To exit press CTRL + C [x] Received b 'python' |
acknowledgment 消息不丢失的方法
- 生产者,代码同上,未改变
- 消费者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import pika import time # 链接rabbit connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) # 创建频道 channel = connection.channel() # 如果生产者没有运行创建队列,那么消费者创建队列,如果队列已存在,创建队列操作会被忽略 channel.queue_declare(queue = 'hello' ) # 回调函数 def callback(ch, method, properties, body): print ( " [x] Received %r" % body) time.sleep( 10 ) print ( 'ok' ) ch.basic_ack(delivery_tag = method.delivery_tag) # 当上面消息处理完成后,通知rabbitmq,消息处理完成,不要在发送了 channel.basic_consume(callback, queue = 'hello' , no_ack = False ) # 表示消费完这个消息后,主动通知rabbitmq完成状态,如果不通知,rabbitmq会把这条消息重新放回队列中,避免丢失 print ( ' [*] Waiting for messages. To exit press CTRL+C' ) channel.start_consuming() |
当生产者生成一条数据,被消费者接收,消费者中断后如果不超过10秒,连接的时候数据还在。当超过10秒后,重新连接,数据将消失。消费者等待连接。
durable 消息不丢失(消息持久化)
这个queue_declare 需要在 生产者(product)和消费者(consumer)代码中都进行设置。
- 生产者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#!/usr/bin/env python import pika # 链接rabbit服务器 connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) # 创建频道 channel = connection.channel() # 创建队列,使用durable方法 channel.queue_declare(queue = 'test' , durable = True ) # 如果想让队列实现持久化那么加上durable=True channel.basic_publish(exchange = '', routing_key = 'test' , body = 'Hello World!' , properties = pika.BasicProperties( delivery_mode = 2 , # 标记我们的消息为持久化的 - 通过设置 delivery_mode 属性为 2,在生产者端持久化 )) # 这个exchange参数就是这个exchange的名字. 空字符串标识默认的或者匿名的exchange:如果存在routing_key, 消息路由到routing_key指定的队列中。 print ( " [x] 开始队列'" ) connection.close() |
- 消费者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#!/usr/bin/env python # -*- coding:utf-8 -*- import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) # 创建频道 channel = connection.channel() # 创建队列,使用durable方法,durable=True 开启持久化 channel.queue_declare(queue = 'test' , durable = True ) def callback(ch, method, properties, body): print ( " [x] Received %r" % body) import time time.sleep( 10 ) print ( 'ok' ) ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_consume(callback, queue = 'hello' , no_ack = False ) print ( ' [*] 等待队列. To exit press CTRL+C' ) channel.start_consuming() |
备注:标记消息为持久化的并不能完全保证消息不会丢失,尽管告诉RabbitMQ保存消息到磁盘,当RabbitMQ接收到消息还没有保存的时候仍然有一个短暂的时间窗口,RabbitMQ不会对每个消息都执行同步fsync(2),可能只是保存到缓存cache还没有写入到磁盘中,这个持久化保证不是很强,但这比我们简单的任务queue要好得多,如果你想要很稳定的消息不丢失,可以使用publisher confirms。
消息顺序获取
默认消息队列里的数据是按照顺序被消费者拿走,例如,消费者1去队列中获取奇数序列任务(分别取任务1,3,5,7),消费者2去队列中获取偶数序列任务(分别取任务2,4,6,8)。如果消费者1处理的任务速度很快,当他完成1,3任务后,消费者2可能2任务还没有处理完,但是消费者1会继续按照排序去取第5个任务而不是第4个任务,完成第五个任务,在执行第七个任务。为了改变这种默认的取任务排序,需要改变参数channel.basic_qos(prefetch_count=1)表示谁来谁取,不在按照奇偶数排列。
- 生产者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters(host = '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 , # 设置消息为持久化的 )) print ( " [x] Sent %r" % message) connection.close() |
- 消费者代码、
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#!/usr/bin/env python 3 # -*- coding:utf-8 -*- import pika import time connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) channel = connection.channel() channel.queue_declare(queue = 'task_queue' ,durable = True ) # 设置队列持久化 def callback(ch, method, properties, body): print ( " [x] Received %r" % body) time.sleep( 10 ) print ( 'ok' ) ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_qos(prefetch_count = 1 ) # 表示谁来谁取,不在按照奇偶数排序 channel.basic_consume(callback, queue = 'task_queue' , no_ack = False ) print ( ' [*] Waiting for messages. To exit press CTRL+C' ) channel.start_consuming() |
发布订阅
- fanout : 所有bind到此exchange的queue都可以接受消息
- direct : 通过routingkey和exchange决定的那个唯一的queue可以接受消息
- topic : 所有符合routingkey(一个表达式)的routingkey所bind的queue
发布订阅和简单的消息队列区别在于,发布订阅会将消息发送给所有的订阅者,而消息队列中的数据被消费一次便消失了。所以,RabbitMQ实现发布和订阅时,会为每一个订阅者创建一个队列,二发布者发布消息时,会将消息放置在所有相关队列中。发布订阅本质上就是发布端将消息发送给了exchange,exchange将消息发送给与它绑定关系的所有队列。
exchange type = fanout 和exchange绑定关系的所有队列都会收到信息
- 发布者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/usr/bin/env python3 import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) channel = connection.channel() channel.exchange_declare(exchange = 'logs' , type = 'fanout' ) # 创建了一个exchange名字叫logs,type=fanout。有了exchange,我们就不需要去创建队列了 message = ' ' .join(sys.argv[ 1 :]) or "info: Hello World!" channel.basic_publish(exchange = 'logs' , routing_key = ' ', body=message) # 指定了exchange后,就不需要指定队列了,所有routing_key=' ' print ( " [x] Sent %r" % message) connection.close() |
- 订阅者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/usr/bin/env python3 import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) channel = connection.channel() channel.exchange_declare(exchange = 'logs' , type = 'fanout' ) # 创建exchange result = channel.queue_declare(exclusive = True ) # 不指定queue名字,随机生成一个唯一的queue,队列断开后自动删除临时队列 queue_name = result.method.queue # 队列名采用服务端分配的临时队列 channel.queue_bind(exchange = 'logs' , queue = queue_name) # 将临时队列和exchange绑定 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() # 保持一直监听的状态 |
关键字发送
- 生产者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#!/usr/bin/env python3 #coding:utf8 #######################生产者################# import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) channel = connection.channel() channel.exchange_declare(exchange = 'direct_logs' , 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() |
- 消费者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#!/usr/bin/env python3 #coding:utf8 import pika import sys ############消费者#### # 连接 connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) channel = connection.channel() channel.exchange_declare(exchange = 'direct_logs' , type = 'direct' ) result = channel.queue_declare(exclusive = True ) queue_name = result.method.queue # serverites 是一个列表,存放关键字,关键字是通过sys.argv获取的 severities = sys.argv[ 1 :] if not severities: sys.stderr.write( "Usage: %s [info] [warning] [error]\n" % sys.argv[ 0 ]) sys.exit( 1 ) # 循环绑定关键字和exchange 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' ) 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() |
模糊匹配
- # 表示可以匹配 0 个或 多个 单词
- * 表示可以匹配到 1个单词
- 消费者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
#!/usr/bin/env python3 #coding:utf8 import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) channel = connection.channel() channel.exchange_declare(exchange = 'topic_logs' , type = 'topic' ) result = channel.queue_declare(exclusive = True ) queue_name = result.method.queue binding_keys = sys.argv[ 1 :] if not binding_keys: sys.stderr.write( "Usage: %s [binding_key]...\n" % sys.argv[ 0 ]) sys.exit( 1 ) for binding_key in binding_keys: channel.queue_bind(exchange = 'topic_logs' , queue = queue_name, routing_key = binding_key) print ( ' [*] Waiting 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() |
- 生产者代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#!/usr/bin/env python3 #coding:utf8 import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost' )) channel = connection.channel() channel.exchange_declare(exchange = 'topic_logs' , type = 'topic' ) routing_key = sys.argv[ 1 ] if len (sys.argv) > 1 else 'anonymous.info' message = ' ' .join(sys.argv[ 2 :]) or 'Hello World!' channel.basic_publish(exchange = 'topic_logs' , routing_key = routing_key, body = message) print ( " [x] Sent %r:%r" % (routing_key, message)) connection.close() |