操作消息队列

作者:操作系统

开卷目录

  • 图示
  • 陈设音讯队列代码
  • 读取新闻队列数据

图示

图片 1

个中P指producer,即生产者;C指consumer,即花费者。中间的浅紫蓝代表新闻队列,实例中表现为HELLO队列。

往队列里插入数据前,查看音讯队列

$sudo rabbitmqctl  list_queues
Listing queues ...
celeryev.db53a5e0-1e6a-4f06-a9f7-2c104c4612fb    0
...done.

布署音讯队列代码

#in_queue.py

#coding=utf8
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

#声明队列,如果消息发送到不存在的队列,rabbitmq会自动清除这些消息
channel.queue_declare(queue='HELLO')

for i in range(10):
    #exchange表示交换器,可以精确的制定消息应发到哪个队列,route_key设置队列的名称,body表示发送的内容
    channel.basic_publish(exchange='', routing_key='HELLO', body='Hello World!' + str(i))
    print " [%d] Sent 'Hello World!'" % i
#关闭连接
connection.close()

推行结果

$python  in_queue.py
 [0] Sent 'Hello World!'
 [1] Sent 'Hello World!'
 [2] Sent 'Hello World!'
 [3] Sent 'Hello World!'
 [4] Sent 'Hello World!'
 [5] Sent 'Hello World!'
 [6] Sent 'Hello World!'
 [7] Sent 'Hello World!'
 [8] Sent 'Hello World!'
 [9] Sent 'Hello World!'

那儿查看音讯队列

$sudo rabbitmqctl  list_queues
Listing queues ...
HELLO    10
celeryev.db53a5e0-1e6a-4f06-a9f7-2c104c4612fb    0
...done.

能够看看队列HELLO里面有10条数据。

读取新闻队列数据

#out_queue.py

#coding=utf8
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

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 out_queue.py 
 [*] Waiting for messages. To exit press CTRL+C
 [x] Received 'Hello World!0'
 [x] Received 'Hello World!1'
 [x] Received 'Hello World!2'
 [x] Received 'Hello World!3'
 [x] Received 'Hello World!4'
 [x] Received 'Hello World!5'
 [x] Received 'Hello World!6'
 [x] Received 'Hello World!7'
 [x] Received 'Hello World!8'
 [x] Received 'Hello World!9'

那时查阅新闻队列

$sudo rabbitmqctl  list_queues
Listing queues ...
HELLO    0
celeryev.db53a5e0-1e6a-4f06-a9f7-2c104c4612fb    0
...done.

能够见见队列HELLO中的数据被读走了,条数为0。

Ubuntu 14.04安装Python 3.3.5  http://www.linuxidc.com/Linux/2014-05/101481.htm

CentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python主旨编制程序 第二版》.(韦斯利 J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python开垦技巧详解》.( 孙东海,宗杰).[高清PDF扫描版+随书录像+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python脚本获取Linux系统音讯 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研商景况 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 语言的升华简史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的详细介绍:请点这里
Python 的下载地址:请点这里

本文永远更新链接地址:http://www.linuxidc.com/Linux/2016-08/134454.htm

图片 2

本文由金冠53777-金冠娱乐53777-Welcome发布,转载请注明来源

关键词: