【Todo】AMQP示例学习
这个网站非常好:
http://www.rabbitmq.com/getstarted.html
把AMQP的各种用法都讲了,还带上了各种语言:
第一篇 http://www.rabbitmq.com/tutorials/tutorial-one-python.html
看到了no_ack=true,那么就不用调用 basic_ack函数了,下面有讲。
Putting it all together
Full code for send.py:
1 |
#!/usr/bin/env python |
Full receive.py code:
1 |
#!/usr/bin/env python |
Now we can try out our programs in a terminal. First, let's send a message using our send.pyprogram:
$ python send.py
[x] Sent 'Hello World!'
The producer program send.py will stop after every run. Let's receive it:
$ python receive.py
[*] Waiting for messages. To exit press CTRL+C
[x] Received 'Hello World!'
Hurray! We were able to send our first message through RabbitMQ. As you might have noticed, the receive.py program doesn't exit. It will stay ready to receive further messages, and may be interrupted with Ctrl-C.
Try to run send.py again in a new terminal.
We've learned how to send and receive a message from a named queue. It's time to move on to part 2 and build a simple work queue.
第二篇 http://www.rabbitmq.com/tutorials/tutorial-two-python.html
讲了之前说的ack机制,以及queue和message的持久化。
Round-robin dispatching
One of the advantages of using a Task Queue is the ability to easily parallelise work. If we are building up a backlog of work, we can just add more workers and that way, scale easily.
First, let's try to run two worker.py scripts at the same time. They will both get messages from the queue, but how exactly? Let's see.
You need three consoles open. Two will run the worker.py script. These consoles will be our two consumers - C1 and C2.
shell1$ python worker.py
[*] Waiting for messages. To exit press CTRL+C
shell2$ python worker.py
[*] Waiting for messages. To exit press CTRL+C
In the third one we'll publish new tasks. Once you've started the consumers you can publish a few messages:
shell3$ python new_task.py First message.
shell3$ python new_task.py Second message..
shell3$ python new_task.py Third message...
shell3$ python new_task.py Fourth message....
shell3$ python new_task.py Fifth message.....
Let's see what is delivered to our workers:
shell1$ python worker.py
[*] Waiting for messages. To exit press CTRL+C
[x] Received 'First message.'
[x] Received 'Third message...'
[x] Received 'Fifth message.....'
shell2$ python worker.py
[*] Waiting for messages. To exit press CTRL+C
[x] Received 'Second message..'
[x] Received 'Fourth message....'
By default, RabbitMQ will send each message to the next consumer, in sequence. On average every consumer will get the same number of messages. This way of distributing messages is called round-robin. Try this out with three or more workers.
第三篇 http://www.rabbitmq.com/tutorials/tutorial-three-python.html
In the previous tutorial we created a work queue. The assumption behind a work queue is that each task is delivered to exactly one worker. In this part we'll do something completely different -- we'll deliver a message to multiple consumers. This pattern is known as "publish/subscribe".
The core idea in the messaging model in RabbitMQ is that the producer never sends any messages directly to a queue. Actually, quite often the producer doesn't even know if a message will be delivered to any queue at all.
There are a few exchange types available: direct, topic, headers and fanout. We'll focus on the last one -- the fanout. Let's create an exchange of that type, and call it logs:
channel.exchange_declare(exchange='logs',
type='fanout')
To find out how to listen for a subset of messages, let's move on to tutorial 4
第四篇 http://www.rabbitmq.com/tutorials/tutorial-four-python.html
We were using a fanout exchange, which doesn't give us too much flexibility - it's only capable of mindless broadcasting.
We will use a direct exchange instead. The routing algorithm behind a direct exchange is simple - a message goes to the queues whose binding key exactly matches the routing key of the message.
It is perfectly legal to bind multiple queues with the same binding key. In our example we could add a binding between X and Q1 with binding key black. In that case, the direct exchange will behave like fanout and will broadcast the message to all the matching queues. A message with routing key black will be delivered to both Q1 and Q2.
但这个direct routing解决不了这个问题:it can't do routing based on multiple criteria.
第五篇 http://www.rabbitmq.com/tutorials/tutorial-five-python.html
Topic exchange
Messages sent to a topic exchange can't have an arbitrary routing_key - it must be a list of words, delimited by dots.
A few valid routing key examples: "stock.usd.nyse", "nyse.vmw", "quick.orange.rabbit". There can be as many words in the routing key as you like, up to the limit of 255 bytes.
- * (star) can substitute for exactly one word.
- # (hash) can substitute for zero or more words.
Topic exchange
Topic exchange is powerful and can behave like other exchanges.
When a queue is bound with "#" (hash) binding key - it will receive all the messages, regardless of the routing key - like in fanout exchange.
When special characters "*" (star) and "#" (hash) aren't used in bindings, the topic exchange will behave just like a direct one.
第六篇 http://www.rabbitmq.com/tutorials/tutorial-six-python.html
RPC
Callback queue
In general doing RPC over RabbitMQ is easy. A client sends a request message and a server replies with a response message. In order to receive a response the client needs to send a 'callback' queue address with the request. Let's try it:
result = channel.queue_declare(exclusive=True)
callback_queue = result.method.queue channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
reply_to = callback_queue,
),
body=request) # ... and some code to read a response message from the callback_queue ...
Message properties
The AMQP protocol predefines a set of 14 properties that go with a message. Most of the properties are rarely used, with the exception of the following:
- delivery_mode: Marks a message as persistent (with a value of 2) or transient (any other value). You may remember this property from the second tutorial.
- content_type: Used to describe the mime-type of the encoding. For example for the often used JSON encoding it is a good practice to set this property to: application/json.
- reply_to: Commonly used to name a callback queue.
- correlation_id: Useful to correlate RPC responses with requests.
The server code is rather straightforward:
- (4) As usual we start by establishing the connection and declaring the queue.
- (11) We declare our fibonacci function. It assumes only valid positive integer input. (Don't expect this one to work for big numbers, it's probably the slowest recursive implementation possible).
- (19) We declare a callback for basic_consume, the core of the RPC server. It's executed when the request is received. It does the work and sends the response back.
- (32) We might want to run more than one server process. In order to spread the load equally over multiple servers we need to set the prefetch_count setting.
注意,如果用的是默认的exchange,那么不需要bind exchange和queue,见第一章、第二章等。
注意rpc client等待回调地方的处理:
while self.response is None:
self.connection.process_data_events()
return int(self.response)
- (32) At this point we can sit back and wait until the proper response arrives.
- (33) And finally we return the response back to the user.
(完)
【Todo】AMQP示例学习的更多相关文章
- MIL 多示例学习 特征选择
一个主要的跟踪系统包含三个成分:1)外观模型,通过其可以估计目标的似然函数.2)运动模型,预测位置.3)搜索策略,寻找当前帧最有可能为目标的位置.MIL主要的贡献在第一条上. MIL与CT的不同在于后 ...
- html5游戏引擎phaser官方示例学习
首发:个人博客,更新&纠错&回复 phaser官方示例学习进行中,把官方示例调整为简明的目录结构,学习过程中加了点中文注释,代码在这里. 目前把官方的完整游戏示例看了一大半, brea ...
- Delphi之通过代码示例学习XML解析、StringReplace的用法(异常控制 good)
*Delphi之通过代码示例学习XML解析.StringReplace的用法 这个程序可以用于解析任何合法的XML字符串. 首先是看一下程序的运行效果: 以解析这样一个XML的字符串为例: <? ...
- 多示例学习 multiple instance learning (MIL)
多示例学习:包(bags) 和 示例 (instance). 包是由多个示例组成的,举个例子,在图像分类中,一张图片就是一个包,图片分割出的patches就是示例.在多示例学习中,包带有类别标签而示例 ...
- AMQP协议学习
参考这个:http://kb.cnblogs.com/page/73759/ 写的挺好 AMQP协议是一种二进制协议,提供客户端应用与消息中间件之间异步.安全.高效地交互.从整体来看,AMQP协议可划 ...
- 通过示例学习rholang(下部:课程8-13)
课程8——状态通道和方法 保存数据 到现在为止,你已经很擅长于发送数据到元组空间和从元组空间中获取数据.但是无论你在什么时候进行计算,你有时需要把一些数据放在一边晚点才使用.几乎所有编程语言都有变量的 ...
- 【Todo】Mybatis学习-偏理论
之前写过好几篇Mybatis相关的文章: http://www.cnblogs.com/charlesblc/p/5906431.html <SSM(SpringMVC+Spring+Myba ...
- ApiDemos示例学习(1)——ApiDemos示例的导入
---恢复内容开始--- 今天准备开始写这个ApiDemos示例的学习日记了,放在网上以监督自己! 首先是导入该示例.如果我们在配置Android开发环境是,利用Android SDK 安装包中的SD ...
- 通过示例学习JavaScript闭包
译者按: 在上一篇博客,我们通过实现一个计数器,了解了如何使用闭包(Closure),这篇博客将提供一些代码示例,帮助大家理解闭包. 原文: JavaScript Closures for Dummi ...
随机推荐
- Android Studio 如何将包名按层级展示
在project视图右上角有个“设置”的按钮,点开,然后将上图所圈部分去勾选就可以了.
- shell查看进程
用shell脚本监控进程是否存在 不存在则启动的实例,先上代码干货: #!/bin/shps -fe|grep processString |grep -v grepif [ $? -ne 0 ]th ...
- Windows环境下google protobuf入门
我使用的是最新版本的protobuf(protobuf-2.6.1),编程工具使用VS2010.简单介绍下google protobuf: google protobuf 主要用于通讯,是google ...
- java解析XML获取城市代码
运行前先导入dom4j架包,由于我们公司用的代理服务器所以下面我设置了代理ip,不需要的可直接忽略 package com.chengshidaima.tools; import java.io.Bu ...
- Opencv基础知识-----视频的读取和操作
Opencv读取视频代码 #include "stdafx.h" #include"highgui.h" int main(int argc,char* a ...
- ueditor 文本编辑器
百度编辑器 压缩包在文件里 百度UEditor编辑器使用教程与使用方法 发布时间:2014-08-23 14:23:34.0 作者:青岛做网站 我们在做网站的时候,网站后台系统一般都会用到 ...
- cell reuse & disposebag
For my project I've made base cell class TableViewCell: UITableViewCell { private(set) var disposeBa ...
- 使用Theos做一个简单的Mobile Substrate Tweak
01 January 2014 Mobile Substrate和Theos Mobile Substrate是Cydia的作者Jay Freeman (@saurik)的另外一个牛X的作品,也叫Cy ...
- android代码实现免提功能
初始化AudioManager: private static AudioManager audioManager; 实现免提功能方法 protected void setSpeekModle() { ...
- PHP中require()文件包含的正确用法
以前看一些PHP框架源码的时候,很奇怪在文件包含的时候,会用dirname(__FILE__)来拼凑文件路 径,不知道这样做有什么好处,后来终于发现了其中的缘由. 我们来看一个简单的例子: 有a,b, ...