在python中引入rabbitmq消息中间件

来源:互联网 发布:水手怕水 知乎 编辑:程序博客网 时间:2024/06/06 20:27

             上周一直在研究zeromq,并且也实现了了zeromq在python和ruby之间的通信,但是如果是一个大型的企业级应用,对消息中间件的要求比较高,比如消息的持久化机制以及系统崩溃恢复等等需求,这个时候zeromq就显得有点鸡肋了,特别是消息持久化是他的的硬伤,那么怎么找一个比较适合的中间件呢?

       目前市场上主流的中间件除了zeromq,还有rabbitmq,activemq等等,这两周都比较有名,一个是基于erlang,一个是基于jms,rabbitmq是AMQP(高级消息队列协议)的标准实现,对于python,ruby等语言都有比较好的支持。

      好吧,那就选择他了,首先我们需要先安装它:

1$ sudo apt-get install rabbitmq-server      -- 一键安装rabbitmq-server
2$ sudo apt-get install python-pip git-core   -- 安装pip
3$ sudo pip install pika==0.9.8                    --- 安装pika
       就这几步就装好啦~!~

装好了以后首先就是测试下

send.py

import pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(        host='localhost'))channel = connection.channel()channel.queue_declare(queue='hello')channel.basic_publish(exchange='',                      routing_key='hello',                      body='Hello World!')print " [x] Sent 'Hello World!'"connection.close()
revecive.py

import pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(        host='localhost'))channel = connection.channel()channel.queue_declare(queue='hello')print ' [*] Waiting for messages. To exit press CTRL+C'def callback(ch, method, properties, body):    print " [x] Received %r" % (body,)channel.basic_consume(callback,                      queue='hello',                      no_ack=True)channel.start_consuming()
运行下:

 $ python send.py [x] Sent 'Hello World!'
 $ python receive.py [*] Waiting for messages. To exit press CTRL+C [x] Received 'Hello World!'
好了测试完毕了,接下来官方网站有很多例子,大家可以找找看看,一共有6中模式,掌握这6种模式基本上算是入门会用了。