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

python16_day11【MQ、Redis、Memcache】

时间:2017-04-04 12:53:27      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:waiting   安装   arch   release   接收   排队   producer   发送数据   python   

一、RabbitMQ

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

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

 

  1.RabbitMQ install

1 安装配置epel源
2    $ rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
3  
4 安装erlang
5    $ yum -y install erlang
6  
7 安装RabbitMQ
8    $ yum -y install rabbitmq-server
  

注意:service rabbitmq-server start/stop

  2. Python API install  

1 pip install pika
2 or
3 easy_install pika
4 or
5 源码
6 https://pypi.python.org/pypi/pika

  3.基于QUEUE实现生产消费模型

 1 import Queue
 2 import threading
 3 
 4 
 5 message = Queue.Queue(10)
 6 
 7 
 8 def producer(i):
 9     while True:
10         message.put(i)
11 
12 
13 def consumer(i):
14     while True:
15         msg = message.get()
16 
17 
18 for i in range(12):
19     t = threading.Thread(target=producer, args=(i,))
20     t.start()
21 
22 for i in range(10):
23     t = threading.Thread(target=consumer, args=(i,))
24     t.start()

  4.基于RabbitMQ

  对于RabbitMQ来说,生产和消费不再针对内存里的一个Queue对象,而是某台服务器上的RabbitMQ Server实现的消息队列。

 1 import pika
 2  
 3 # ######################### 生产者 #########################
 4  
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(
 6         host=localhost))
 7 channel = connection.channel()
 8  
 9 channel.queue_declare(queue=hello)
10  
11 channel.basic_publish(exchange=‘‘,
12                       routing_key=hello,
13                       body=Hello World!)
14 print(" [x] Sent ‘Hello World!‘")
15 connection.close()
16 
17 
18  
19 # ########################## 消费者 ##########################
20 import pika
21 connection = pika.BlockingConnection(pika.ConnectionParameters(
22         host=localhost))
23 channel = connection.channel()
24  
25 channel.queue_declare(queue=hello)
26  
27 def callback(ch, method, properties, body):
28     print(" [x] Received %r" % body)
29  
30 channel.basic_consume(callback,
31                       queue=hello,
32                       no_ack=True)
33  
34 print( [*] Waiting for messages. To exit press CTRL+C)
35 channel.start_consuming()

 

python16_day11【MQ、Redis、Memcache】

标签:waiting   安装   arch   release   接收   排队   producer   发送数据   python   

原文地址:http://www.cnblogs.com/weibiao/p/6664553.html

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