(转)ZeroMQ简介 ----高效消息队列项目
Zeromq模式:
http://blog.codingnow.com/2011/02/zeromq_message_patterns.html
zeromq主页:
Zeromq Guild:
http://zguide.zeromq.org/page:all#Fixing-the-World
Zeromq 中文简介:
http://blog.csdn.net/program_think/article/details/6687076
Zero wiki:
http://en.wikipedia.org/wiki/%C3%98MQ
zeromq系列:
http://iyuan.iteye.com/blog/972949
Zeromq资源阅读:ØMQ(Zeromq) 是一个更为高效的传输层
优势是:
1 程序接口库是一个并发框架
2 在集群和超级计算机上表现得比TCP更快
3 通过inproc, IPC, TCP, 和 multicast进行传播消息
4 通过发散,订阅,流水线,请求的方式连接
5 对于不定规模的多核消息传输应用使用异步IO
6 有非常大并且活跃的开源社区
7 支持30+的语言
8 支持多种系统
Zeromq定义为“史上最快的消息队列”
从网络通信的角度看,它处于会话层之上,应用层之下。
ØMQ (ZeroMQ, 0MQ, zmq) looks like an embeddable networking library but acts like a concurrency framework. It gives you sockets that carry whole messages across various transports like in-process, inter-process, TCP, and multicast. You can connect sockets N-to-N with patterns like fanout, pub-sub, task distribution, and request-reply. It's fast enough to be the fabric for clustered products. Its asynchronous I/O model gives you scalable multicore applications, built as asynchronous message-processing tasks. It has a score of language APIs and runs on most operating systems. ØMQ is from iMatix and is LGPL open source.
Zeromq中传递的数据格式是由用户自己负责,就是说如果server发送的string是有带"\0"的,那么client就必须要知道有这个
Pub_Sub模式。
the subscriber will always miss the first messages that the publisher sends. This is because as the subscriber connects to the publisher (something that takes a small but non-zero time), the publisher may already be sending messages out.
在这种模式下很可能发布者刚启动时发布的数据出现丢失,原因是用zmq发送速度太快,在订阅者尚未与发布者建立联系时,已经开始了数据发布(内部局域网没这么夸张的)。官网给了两个解决方案;1,发布者sleep一会再发送数据(这个被标注成愚蠢的);2,使用proxy。
Zeromq示例:1 获取例子
git clone --depth=1 git://github.com/imatix/zguide.git
2 服务器端:
(当服务器收到消息的时候,服务器回复“World”)
|
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
|
<?php
/*
* Hello World server
* Binds REP socket to tcp://*:5555
* Expects "Hello" from client, replies with "World"
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*/
$context = new ZMQContext(1);
// Socket to talk to clients
$responder = new ZMQSocket($context, ZMQ::SOCKET_REP);
$responder->bind("tcp://*:5555");
while(true) {
// Wait for next request from client
$request = $responder->recv();
printf ("Received request: [%s]\n", $request);
// Do some 'work'
sleep (1);
// Send reply back to client
$responder->send("World");
}
|
3 客户端:
(客户端发送消息)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<?php
/*
* Hello World client
* Connects REQ socket to tcp://localhost:5555
* Sends "Hello" to server, expects "World" back
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*/
$context = new ZMQContext();
// Socket to talk to server
echo "Connecting to hello world server…\n";
$requester = new ZMQSocket($context, ZMQ::SOCKET_REQ);
$requester->connect("tcp://localhost:5555");
for($request_nbr = 0; $request_nbr != 10; $request_nbr++) {
printf ("Sending request %d…\n", $request_nbr);
$requester->send("Hello");
$reply = $requester->recv();
printf ("Received reply %d: [%s]\n", $request_nbr, $reply);
}
|
|
1
|
|
天气气候订阅系统:(pub-sub)
1 server端:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?php
/*
* Weather update server
* Binds PUB socket to tcp://*:5556
* Publishes random weather updates
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*/
// Prepare our context and publisher
$context = new ZMQContext();
$publisher = $context->getSocket(ZMQ::SOCKET_PUB);
$publisher->bind("tcp://*:5556");
$publisher->bind("ipc://weather.ipc");
while (true) {
// Get values that will fool the boss
$zipcode = mt_rand(0, 100000);
$temperature = mt_rand(-80, 135);
$relhumidity = mt_rand(10, 60);
// Send message to all subscribers
$update = sprintf ("%05d %d %d", $zipcode, $temperature, $relhumidity);
$publisher->send($update);
}
|
2 client端:
|
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
|
<?php
/*
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and finds avg temp in zipcode
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*/
$context = new ZMQContext();
// Socket to talk to server
echo "Collecting updates from weather server…", PHP_EOL;
$subscriber = new ZMQSocket($context, ZMQ::SOCKET_SUB);
$subscriber->connect("tcp://localhost:5556");
// Subscribe to zipcode, default is NYC, 10001
$filter = $_SERVER['argc'] > 1 ? $_SERVER['argv'][1] : "10001";
$subscriber->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, $filter);
// Process 100 updates
$total_temp = 0;
for ($update_nbr = 0; $update_nbr < 100; $update_nbr++) {
$string = $subscriber->recv();
sscanf ($string, "%d %d %d", $zipcode, $temperature, $relhumidity);
$total_temp += $temperature;
}
printf ("Average temperature for zipcode '%s' was %dF\n",
$filter, (int) ($total_temp / $update_nbr));
|
|
1
|
------------------------
|
|
1
|
pub-sub的proxy模式:
|
|
1
|
图示是:
|
Proxy节点的代码:
|
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
|
<?php
/*
* Weather proxy device
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*/
$context = new ZMQContext();
// This is where the weather server sits
$frontend = new ZMQSocket($context, ZMQ::SOCKET_SUB);
$frontend->connect("tcp://192.168.55.210:5556");
// This is our public endpoint for subscribers
$backend = new ZMQSocket($context, ZMQ::SOCKET_PUB);
$backend->bind("tcp://10.1.1.0:8100");
// Subscribe on everything
$frontend->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, "");
// Shunt messages out to our own subscribers
while(true) {
while(true) {
// Process all parts of the message
$message = $frontend->recv();
$more = $frontend->getSockOpt(ZMQ::SOCKOPT_RCVMORE);
$backend->send($message, $more ? ZMQ::SOCKOPT_SNDMORE : 0);
if(!$more) {
break; // Last message part
}
}
}
|
----------------------
作者:yjf512(轩脉刃)
出处:http://www.cnblogs.com/yjf512/
★ZMQ是啥玩意儿? 通俗地说,ZMQ是一个开源的、跨语言的、非常简洁的、非常高性能、非常灵活的网络通讯库。
它的官方网站在"这里",维基百科的介绍在"这里"(暂时没有中文的维基词条)。
这玩意儿推出的时间不长,貌似09年下半年才推出1.0.1版本。俺去年开始接触它,感觉实在不错,今年就已经用于公司的产品中。最近一段时间,对 ZMQ 的好评日渐增多,所以俺也来赶赶潮流,在俺博客里忽悠一下。
接下来,就针对ZMQ的几大特点,分别聊一聊。
★简单 ZMQ的首要特点,就是简单(从它的名字也能感觉得到)。
◇封装导致的简单
相比原始的 socket API,ZMQ 封装掉了很多东西,免去了开发人员的很多麻烦。
比如,传统的 TCP 是基于字节流进行收发,因此程序猿常常要自己去处理数据块与数据块之间的边界(断界处理);与之相对,ZMQ 是以消息为单位进行收发,它确保你每次发出/收到的,都是一个消息块。这样一来,就省却了不少代码量。
比如,基于 socket API 进行 TCP 通讯,你需要自己处理很多网络异常(比如连接异常中断以及重连),即使有经验的程序员,也未必能写得严密。而在 ZMQ 中,这些琐事统统不用程序猿操心。
再比如,用传统的 socket API,当你想提高通讯性能,往往要搞些异步(非阻塞)、缓冲区、多线程之类的把戏。而这些东西,ZMQ 也帮你封装掉了。
总而言之,ZMQ 对很多底层细节的封装,让你的网络程序代码变得简单,写起来又快又轻松。
◇API的简单
ZMQ 的 API 接口很少,而且在风格上非常类似于 BSD Socket。如果你曾经用 socket API 写过程序,那要上手 ZMQ 是非常容易的。如果你是 Java 程序猿,搞过 JMS API(比如 ActiveMQ),那你会发觉两者的 API 简直是天壤之别。顺便抱怨一下:Java 的 JMS API,那可真是复杂啊!
◇具体的示例
为了增加说服力,下面给出 Python 语言实现的 Echo Server 代码(所谓的Echo Server,是一种最简单的服务端程序。它把收到的信息原样回送给客户端程序)。
#服务端程序
import zmq
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://127.0.0.1:1234")
while True :
msg = socket.recv()
socket.send(msg)
#客户端端程序
import zmq
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://127.0.0.1:1234")
msg_send = "xxx"socket.send(msg_send)
print "Send:", msg_send
msg_recv = socket.recv()
print "Receive:", msg_recv
从上述示例代码,大伙儿应该能感觉到:ZMQ 的使用,是非常简单的。
★灵活 所谓的灵活性,主要指如下2方面。
◇适用于多种通讯环境
ZMQ 可以灵活地支持多种通讯环境(进程内,主机内跨进程、跨主机)。ZMQ 的 API 设计得很好,以至于你的代码只要做很小的改动(甚至不改动),就可以适用于不同的通讯环境。
在刚才的例子里,有这样的语句 socket.connect("tcp://127.0.0.1:1234")。其中的 "tcp://127.0.0.1:1234" 是表示通讯对端的地址串。ZMQ 约定地址串使用如下格式:transport://endpoint 。地址串前面的 transport 表示通讯的类型,目前支持 inproc(进程内),ipc(主机内跨进程),tcp(跨主机),pgm(跨主机,支持多播)共4种方式。
对程序猿来说,如果你把通讯的地址串保存到配置文件中,就完全可以用一套代码来搞定多种通讯方式,非常爽!
◇支持多种通讯模式
ZMQ将常见的通讯场景进行了归纳,总结了如下几种不同的模式。
PUB and SUB
REQ and REP
REQ and ROUTER
DEALER and REP
DEALER and ROUTER
DEALER and DEALER
ROUTER and ROUTER
PUSH and PULL
PAIR and PAIR
限于篇幅,俺就不深入介绍每种模式了,有兴趣的同学请看官方文档(在"这里")。
★跨语言 为啥俺要强调跨语言的特色捏?通常来说,用得着网络通讯库的软件系统,某种程度上都算是分布式系统。如果开发的分布式系统比较复杂,要想用一种编程语言通吃,难度较大。因此,在稍微复杂的分布式系统中,采用多种编程语言是常有的事儿(至少俺的经历是如此)。所以,ZMQ 的这个跨语言特色就显得非常重要了。
在官方网站的文档中,给出了如下许多编程语言的示例(链接在"这里")。为避免引发编程语言的名次之争,以下按照字母序排列。
Ada, Basic, C#, C, C++, Common Lisp, Erlang, Go, Haskell, Haxe, Java, JavaScript(Node.js), Lua, Objective-C, PHP, Perl, Python, Racket, Ruby, Scala
这个语言清单太全了,居然有2个语言,俺都没听说过。可以不夸张地说——常用的编程语言,都可以找到相应的 ZMQ 封装库。
★高性能 说到性能,这可是 ZMQ 吹嘘的主要亮点。首先,ZMQ 是用 C/C++ 开发的(C/C++ 的性能,那可是公认滴);其次,ZMQ 本身的协议格式定义得很简洁(相对来说,JMS 规范中的协议格式就复杂多了)。所以,它的性能远远高于其它的消息队列软件。甚至可以说,用 ZMQ 的性能,跟用传统 socket API 的性能,是不相上下滴。
为了让大伙儿有一个感性的认识,俺特地找来了消息队列软件的性能测评。这是某老外写的一篇帖子(在"这里"),不懂洋文的同学可以看"这里"。连帖子都懒得看的同学,可以直接看下图。
从图中可以明显看出,ZMQ 相比其它几款MQ,简直是鹤立鸡群啊!性能根本不在一个档次嘛。
★总结 总体而言,ZMQ 是非常值得大伙儿去尝试的一个网络通讯库。即使工作中用不到,业余时间玩玩也是不错滴。
本帖子发出后,如果感兴趣的人较多,俺会根据反馈,再聊一些深入的话题。
![clip_image001_thumb[2] clip_image001_thumb[2]](http://images.cnblogs.com/cnblogs_com/yjf512/201203/201203030842035841.png)
浙公网安备 33010602011771号