RabbitMQ
RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。
MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。
RabbitMQ安装
`安装配置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``-``server`
注意:service rabbitmq-server start/stop
安装API
`pip install pika``or``easy_install pika``or``源码` `https:``/``/``pypi.python.org``/``pypi``/``pika`
使用API操作RabbitMQ
基于Queue实现生产者消费者模型
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import Queue
import threading
message = Queue.Queue(10)
def producer(i):
while True:
message.put(i)
def consumer(i):
while True:
msg = message.get()
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来说,生产和消费不再针对内存里的一个Queue对象,而是某台服务器上的RabbitMQ Server实现的消息队列。
`#!/usr/bin/env python``import` `pika` `# ######################### 生产者 #########################` `connection ``=` `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!'"``)``conn