python笔记10

rabbitmq消息队列

server端

 1 #!/usr/bin/env python
 2 import pika
 3
 4 connection = pika.BlockingConnection(pika.ConnectionParameters(
 5                ‘localhost‘))
 6 channel = connection.channel()
 7
 8 #声明queue
 9 channel.queue_declare(queue=‘hello‘)
10
11 #n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
12 channel.basic_publish(exchange=‘‘,
13                       routing_key=‘hello‘,
14                       body=‘Hello World!‘)
15 print(" [x] Sent ‘Hello World!‘")
16 connection.close()

send

client端

 1 #_*_coding:utf-8_*_
 2 __author__ = ‘Alex Li‘
 3 import pika
 4
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6                ‘localhost‘))
 7 channel = connection.channel()
 8
 9
10 #You may ask why we declare the queue again ? we have already declared it in our previous code.
11 # We could avoid that if we were sure that the queue already exists. For example if send.py program
12 #was run before. But we‘re not yet sure which program to run first. In such cases it‘s a good
13 # practice to repeat declaring the queue in both programs.
14 channel.queue_declare(queue=‘hello‘)
15
16 def callback(ch, method, properties, body):
17     print(" [x] Received %r" % body)
18
19 channel.basic_consume(callback,
20                       queue=‘hello‘,
21                       no_ack=True)
22
23 print(‘ [*] Waiting for messages. To exit press CTRL+C‘)
24 channel.start_consuming()

received

rabbitmq工作模式:

1、Work Queues

在这种模式下,RabbitMQ会默认把p发的消息依次分发给各个消费者(c),跟负载均衡差不多

server端

 1 import pika
 2
 3 connection = pika.BlockingConnection(pika.ConnectionParameters(
 4                ‘localhost‘))
 5 channel = connection.channel()
 6
 7 #声明queue
 8 channel.queue_declare(queue=‘task_queue‘)
 9
10 #n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
11 import sys
12
13 message = ‘ ‘.join(sys.argv[1:]) or "Hello World!"
14 channel.basic_publish(exchange=‘‘,
15                       routing_key=‘task_queue‘,
16                       body=message,
17                       properties=pika.BasicProperties(
18                       delivery_mode = 2, # make message persistent
19                       ))
20 print(" [x] Sent %r" % message)
21 connection.close()

send

client端

 1 import pika,time
 2
 3 connection = pika.BlockingConnection(pika.ConnectionParameters(
 4                ‘localhost‘))
 5 channel = connection.channel()
 6
 7
 8
 9 def callback(ch, method, properties, body):
10     print(" [x] Received %r" % body)
11     time.sleep(body.count(b‘.‘))
12     print(" [x] Done")
13     ch.basic_ack(delivery_tag = method.delivery_tag)
14
15
16 channel.basic_consume(callback,
17                       queue=‘task_queue‘,
18                       )
19
20 print(‘ [*] Waiting for messages. To exit press CTRL+C‘)
21 channel.start_consuming()

received

ch.basic_ack(delivery_tag = method.delivery_tag)

接收端主动向服务器发送确认请求

此时,先启动消息生产者,然后再分别启动3个消费者,通过生产者多发送几条消息,你会发现,这几条消息会被依次分配到各个消费者身上  

Doing a task can take a few seconds. You may wonder what happens if one of the consumers starts a long task and dies with it only partly done. With our current code once RabbitMQ delivers message to the customer it immediately removes it from memory. In this case, if you kill a worker we will lose the message it was just processing. We‘ll also lose all the messages that were dispatched to this particular worker but were not yet handled.

But we don‘t want to lose any tasks. If a worker dies, we‘d like the task to be delivered to another worker.

In order to make sure a message is never lost, RabbitMQ supports message acknowledgments. An ack(nowledgement) is sent back from the consumer to tell RabbitMQ that a particular message had been received, processed and that RabbitMQ is free to delete it.

If a consumer dies (its channel is closed, connection is closed, or TCP connection is lost) without sending an ack, RabbitMQ will understand that a message wasn‘t processed fully and will re-queue it. If there are other consumers online at the same time, it will then quickly redeliver it to another consumer. That way you can be sure that no message is lost, even if the workers occasionally die.

There aren‘t any message timeouts; RabbitMQ will redeliver the message when the consumer dies. It‘s fine even if processing a message takes a very, very long time.

Message acknowledgments are turned on by default. In previous examples we explicitly turned them off via the no_ack=True flag. It‘s time to remove this flag and send a proper acknowledgment from the worker, once we‘re done with a task.

1 def callback(ch, method, properties, body):
2     print " [x] Received %r" % (body,)
3     time.sleep( body.count(‘.‘) )
4     print " [x] Done"
5     ch.basic_ack(delivery_tag = method.delivery_tag)
6
7 channel.basic_consume(callback,
8                       queue=‘hello‘)

callback

Using this code we can be sure that even if you kill a worker using CTRL+C while it was processing a message, nothing will be lost. Soon after the worker dies all unacknowledged messages will be redelivered

2、消息持久化

We have learned how to make sure that even if the consumer dies, the task isn‘t lost(by default, if wanna disable  use no_ack=True). But our tasks will still be lost if RabbitMQ server stops.

When RabbitMQ quits or crashes it will forget the queues and messages unless you tell it not to. Two things are required to make sure that messages aren‘t lost: we need to mark both the queue and messages as durable.

First, we need to make sure that RabbitMQ will never lose our queue. In order to do so, we need to declare it as durable:

1 channel.queue_declare(queue=‘hello‘, durable=True)

Although this command is correct by itself, it won‘t work in our setup. That‘s because we‘ve already defined a queue called hello which is not durable. RabbitMQ doesn‘t allow you to redefine an existing queue with different parameters and will return an error to any program that tries to do that. But there is a quick workaround - let‘s declare a queue with different name, for exampletask_queue:

1 channel.queue_declare(queue=‘task_queue‘, durable=True)

At that point we‘re sure that the task_queue queue won‘t be lost even if RabbitMQ restarts. Now we need to mark our messages as persistent - by supplying a delivery_mode property with a value 2

1 channel.basic_publish(exchange=‘‘,
2                       routing_key="task_queue",
3                       body=message,
4                       properties=pika.BasicProperties(
5                          delivery_mode = 2, # make message persistent
6                       ))

3、消息公平分发

如果Rabbit只管按顺序把消息发到各个消费者身上,不考虑消费者负载的话,很可能出现,一个机器配置不高的消费者那里堆积了很多消息处理不完,同时配置高的消费者却一直很轻松。为解决此问题,可以在各个消费者端,配置perfetch=1,意思就是告诉RabbitMQ在我这个消费者当前消息还没处理完的时候就不要再给我发新消息了。

带消息持久化+公平分发的完整代码

 1 #!/usr/bin/env python
 2 import pika
 3 import sys
 4
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6         host=‘localhost‘))
 7 channel = connection.channel()
 8
 9 channel.queue_declare(queue=‘task_queue‘, durable=True)
10
11 message = ‘ ‘.join(sys.argv[1:]) or "Hello World!"
12 channel.basic_publish(exchange=‘‘,
13                       routing_key=‘task_queue‘,
14                       body=message,
15                       properties=pika.BasicProperties(
16                          delivery_mode = 2, # make message persistent
17                       ))
18 print(" [x] Sent %r" % message)
19 connection.close()

send

 1 #!/usr/bin/env python
 2 import pika
 3 import time
 4
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6         host=‘localhost‘))
 7 channel = connection.channel()
 8
 9 channel.queue_declare(queue=‘task_queue‘, durable=True)
10 print(‘ [*] Waiting for messages. To exit press CTRL+C‘)
11
12 def callback(ch, method, properties, body):
13     print(" [x] Received %r" % body)
14     time.sleep(body.count(b‘.‘))
15     print(" [x] Done")
16     ch.basic_ack(delivery_tag = method.delivery_tag)
17
18 channel.basic_qos(prefetch_count=1)
19 channel.basic_consume(callback,
20                       queue=‘task_queue‘)
21
22 channel.start_consuming()

received

4、publish\subscribe

之前的例子都基本都是1对1的消息发送和接收,即消息只能发送到指定的queue里,但有些时候你想让你的消息被所有的Queue收到,类似广播的效果,这时候就要用到exchange了,

An exchange is a very simple thing. On one side it receives messages from producers and the other side it pushes them to queues. The exchange must know exactly what to do with a message it receives. Should it be appended to a particular queue? Should it be appended to many queues? Or should it get discarded. The rules for that are defined by the exchange type.

Exchange在定义的时候是有类型的,以决定到底是哪些Queue符合条件,可以接收消息

fanout: 所有bind到此exchange的queue都可以接收消息
direct: 通过routingKey和exchange决定的那个唯一的queue可以接收消息
topic:所有符合routingKey(此时可以是一个表达式)的routingKey所bind的queue可以接收消息

   表达式符号说明:#代表一个或多个字符,*代表任何字符
      例:#.a会匹配a.a,aa.a,aaa.a等
          *.a会匹配a.a,b.a,c.a等
     注:使用RoutingKey为#,Exchange Type为topic的时候相当于使用fanout 

headers: 通过headers 来决定把消息发给哪些queue

 1 #!/usr/bin/env python
 2 import pika
 3 import sys
 4
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6         host=‘localhost‘))
 7 channel = connection.channel()
 8
 9 channel.queue_declare(queue=‘task_queue‘, durable=True)
10
11 message = ‘ ‘.join(sys.argv[1:]) or "Hello World!"
12 channel.basic_publish(exchange=‘‘,
13                       routing_key=‘task_queue‘,
14                       body=message,
15                       properties=pika.BasicProperties(
16                          delivery_mode = 2, # make message persistent
17                       ))
18 print(" [x] Sent %r" % message)
19 connection.close()

publisher

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

subscriber

5、有选择的消息接收

RabbitMQ支持根据关键字发送,即:队列绑定关键字,发送者将数据根据关键字发送到消息exchange,exchange根据 关键字 判定应该将数据发送至指定队列。

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

publisher

 1 import pika
 2 import sys
 3
 4 connection = pika.BlockingConnection(pika.ConnectionParameters(
 5         host=‘localhost‘))
 6 channel = connection.channel()
 7
 8 channel.exchange_declare(exchange=‘direct_logs‘,
 9                          type=‘direct‘)
10
11 result = channel.queue_declare(exclusive=True)
12 queue_name = result.method.queue
13
14 severities = sys.argv[1:]
15 if not severities:
16     sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
17     sys.exit(1)
18
19 for severity in severities:
20     channel.queue_bind(exchange=‘direct_logs‘,
21                        queue=queue_name,
22                        routing_key=severity)
23
24 print(‘ [*] Waiting for logs. To exit press CTRL+C‘)
25
26 def callback(ch, method, properties, body):
27     print(" [x] %r:%r" % (method.routing_key, body))
28
29 channel.basic_consume(callback,
30                       queue=queue_name,
31                       no_ack=True)
32
33 channel.start_consuming()

received

更细致的消息过滤

Although using the direct exchange improved our system, it still has limitations - it can‘t do routing based on multiple criteria.

In our logging system we might want to subscribe to not only logs based on severity, but also based on the source which emitted the log. You might know this concept from the syslog unix tool, which routes logs based on both severity (info/warn/crit...) and facility (auth/cron/kern...).

That would give us a lot of flexibility - we may want to listen to just critical errors coming from ‘cron‘ but also all logs from ‘kern‘.

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

publisher

 1 import pika
 2 import sys
 3
 4 connection = pika.BlockingConnection(pika.ConnectionParameters(
 5         host=‘localhost‘))
 6 channel = connection.channel()
 7
 8 channel.exchange_declare(exchange=‘topic_logs‘,
 9                          type=‘topic‘)
10
11 result = channel.queue_declare(exclusive=True)
12 queue_name = result.method.queue
13
14 binding_keys = sys.argv[1:]
15 if not binding_keys:
16     sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
17     sys.exit(1)
18
19 for binding_key in binding_keys:
20     channel.queue_bind(exchange=‘topic_logs‘,
21                        queue=queue_name,
22                        routing_key=binding_key)
23
24 print(‘ [*] Waiting for logs. To exit press CTRL+C‘)
25
26 def callback(ch, method, properties, body):
27     print(" [x] %r:%r" % (method.routing_key, body))
28
29 channel.basic_consume(callback,
30                       queue=queue_name,
31                       no_ack=True)
32
33 channel.start_consuming()

subscriber

6、Remote procedure call (RPC)

To illustrate how an RPC service could be used we‘re going to create a simple client class. It‘s going to expose a method named call which sends an RPC request and blocks until the answer is received:

 1 #_*_coding:utf-8_*_
 2 __author__ = ‘Alex Li‘
 3 import pika
 4 import time
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6         host=‘localhost‘))
 7
 8 channel = connection.channel()
 9
10 channel.queue_declare(queue=‘rpc_queue‘)
11
12 def fib(n):
13     if n == 0:
14         return 0
15     elif n == 1:
16         return 1
17     else:
18         return fib(n-1) + fib(n-2)
19
20 def on_request(ch, method, props, body):
21     n = int(body)
22
23     print(" [.] fib(%s)" % n)
24     response = fib(n)
25
26     ch.basic_publish(exchange=‘‘,
27                      routing_key=props.reply_to,
28                      properties=pika.BasicProperties(correlation_id = 29                                                          props.correlation_id),
30                      body=str(response))
31     ch.basic_ack(delivery_tag = method.delivery_tag)
32
33 channel.basic_qos(prefetch_count=1)
34 channel.basic_consume(on_request, queue=‘rpc_queue‘)
35
36 print(" [x] Awaiting RPC requests")
37 channel.start_consuming()

serevr

 1 import pika
 2 import uuid
 3
 4 class FibonacciRpcClient(object):
 5     def __init__(self):
 6         self.connection = pika.BlockingConnection(pika.ConnectionParameters(
 7                 host=‘localhost‘))
 8
 9         self.channel = self.connection.channel()
10
11         result = self.channel.queue_declare(exclusive=True)
12         self.callback_queue = result.method.queue
13
14         self.channel.basic_consume(self.on_response, no_ack=True,
15                                    queue=self.callback_queue)
16
17     def on_response(self, ch, method, props, body):
18         if self.corr_id == props.correlation_id:
19             self.response = body
20
21     def call(self, n):
22         self.response = None
23         self.corr_id = str(uuid.uuid4())
24         self.channel.basic_publish(exchange=‘‘,
25                                    routing_key=‘rpc_queue‘,
26                                    properties=pika.BasicProperties(
27                                          reply_to = self.callback_queue,
28                                          correlation_id = self.corr_id,
29                                          ),
30                                    body=str(n))
31         while self.response is None:
32             self.connection.process_data_events()
33         return int(self.response)
34
35 fibonacci_rpc = FibonacciRpcClient()
36
37 print(" [x] Requesting fib(30)")
38 response = fibonacci_rpc.call(30)
39 print(" [.] Got %r" % response)

client

更细致的消息过滤

时间: 2024-10-05 11:15:25

python笔记10的相关文章

Python 笔记 #10# Histograms

1.Build a histogram In [1]: help(plt.hist) Help on function hist in module matplotlib.pyplot: hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, lo

python基础教程_学习笔记10:异常

异常 什么是异常 Python用异常对象来表示异常情况.遇到错误后,会引发异常.如果异常对象并未被处理或捕捉,程序就会用所谓的回溯(Traceback,一种错误信息)终止执行: >>> 1/0 Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 1/0 ZeroDivisionError: integer division or modulo by

Python笔记_01列表 和元祖

Python笔记 第一章 列表和元祖 1.通用序列操作 所有序列都可以进行某些特定操作,包括:索引(indexing).分片(slicing).加(adding).乘(multiplying)以及检查某元素是否属于列表成员. 迭代:依次对序列中的每个元素重复执行某些操作. 序列的索引:通过元素在列表中的位置可以定位到该元素,这就是列表的索引,使用类似于list[0]对元素进行索引,索引0指向第一个元素.也可使用负数对元素进行索引,使用负数对元素索引时,列表中的最后一个元素由-1表示,例如list

玩蛇(Python)笔记之基础Part3

玩蛇(Python)笔记之基础Part1 一.集合 1.set 无序,不重复序列 {}创建,直接写元素 2.set功能 __init__()构造方法,,使用强制转换就会调用此方法 1 set1 = {'year', 'jiujiujiu'} 2 print(type(set1)) 3 # 创建集合 4 s = set() # 创建空集合 5 li = [11, 22, 11, 22] 6 s = set(li) set 3.集合的基本操作 1 # 操作集合 2 s1 = set() 3 s1.a

Python笔记(四)

在<Python笔记(三)>中,我记录关于Python中序列问题的知识.个人觉得确实比Java中的集合框架简单.之前也说了,Python是一种高级面向对象的语言,它的每一个变量都称为对象.今天我接触了面向对象的编程.下面是这篇博客的目录: 1.类与对象 2.输入输出 3.异常 类与对象: 我们都知道面向对象的语言具备四个特性:抽象,继承,封装,多态.Java,C++是这样,Python也不例外.在Python中,我们定义一个类,使用关键字class.形式如下:class classname:.

Python笔记之不可不练

如果您已经有了一定的Python编程基础,那么本文就是为您的编程能力锦上添花,如果您刚刚开始对Python有一点点兴趣,不怕,Python的重点基础知识已经总结在博文<Python笔记之不可不知>中,尽管本文是自己学习Python过程中的总结,在大神看来,或许略欠火候,希望批评指正,万分感谢! 本文是作者学习成绩的见证,请尊重劳动成果!版权归作者和博客园共有,欢迎转载,但请保留本文出处http://www.cnblogs.com/itred/p/4687287.html ,  作者:itRed

玩蛇(Python)笔记之基础Part2

玩蛇(Python)笔记之基础Part2 一.列表 1.列表 别的语言叫数组 python牛逼非要取个不一样的名字 1 age = 23 2 name = ["biubiubiu", "jiujiujiu", 22, age] 3 # namecopy = name 4 # namecopy.pop() 5 print(name) 6 # print(namecopy) List 2.列表取值 正常index 从零开始,,取倒数加负号 倒数第一就是[-1] 3.列表

python笔记 - day8

python笔记 - day8 参考: http://www.cnblogs.com/wupeiqi/p/4766801.html http://www.cnblogs.com/wupeiqi/articles/5017742.html 大纲 面向对象三大特性之多态 类成员之静态字段和普通字段 类成员之普通方法和静态方法以及类方法 类成员之属性 类成员之成员修饰符 类成员之特殊成员 其他之isinstance和issubclass 其他之super的应用 实例之自定义有序字典 单例模式 基本异常

Python笔记——类定义

Python笔记——类定义 一.类定义: class <类名>: <语句> 类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性 如果直接使用类名修改其属性,那么将直接影响到已经实例化的对象 类的私有属性: __private_attrs  两个下划线开头,声明该属性为私有,不能在类地外部被使用或直接访问 在类内部的方法中使用时 self.__private_attrs 类的方法 在类地内部,使用def关键字可以为类定义一个方法,与一般函数定义不同,类方法必须