码迷,mamicode.com
首页 > 编程语言 > 详细

Python 操作RabbitMQ

时间:2016-06-12 00:14:52      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

 

RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。

MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。

 

RabbitMQ安装

yum安装   你也可以使用源码安装

安装配置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

实现最简单的队列通信

send端

#!/usr/bin/env python
import pika
 
connection = pika.BlockingConnection(pika.ConnectionParameters(
               localhost))
channel = connection.channel()
 
#声明queue
channel.queue_declare(queue=hello)
 
#n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange=‘‘,
                      routing_key=hello,
                      body=Hello World!)
print(" [x] Sent ‘Hello World!‘")
connection.close()

receive端

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

 

Python 操作RabbitMQ

标签:

原文地址:http://www.cnblogs.com/yexiaochong/p/5576227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!