码迷,mamicode.com
首页 > 其他好文 > 详细

RabbitMQ之入门

时间:2016-09-22 12:59:44      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

生成者:

#coding:utf-8
__author__ = similarface

import pika,sys
#连接RabbitMQ
credentials = pika.PlainCredentials(guest,guest)
conn_params = pika.ConnectionParameters(localhost,credentials=credentials)
conn_broker=pika.BlockingConnection(conn_params)

#获取信道
channel=conn_broker.channel()

#声明交换器
channel.exchange_declare(exchange="hello-exchange",type="direct",passive=False
                         ,durable=True,auto_delete=False
                         )

#创建消息
msg="hello world"
msg_props=pika.BasicProperties()
msg_props.content_type="text/plain"

#发布消息
for i in xrange(10000):
    channel.basic_publish(body=msg+str(i),exchange="hello-exchange",properties=msg_props,routing_key="hola")

 

消费者:

#coding:utf-8
__author__ = similarface
import pika
#建立到代理服务器的连接
credentials=pika.PlainCredentials(guest,guest)
conn_params=pika.ConnectionParameters("localhost",credentials=credentials)
conn_broker=pika.BlockingConnection(conn_params)

#获取信道
channel=conn_broker.channel()

#声明交换器
channel.exchange_declare(exchange="hello-exchange",type="direct",passive=False
                         ,durable=True,auto_delete=False)

#声明队列
channel.queue_declare(queue="hello-queue")

#通过键hola 将队列和交换器绑定
channel.queue_bind(queue="hello-queue",exchange="hello-exchange",routing_key="hola")

#用于处理传入消息的函数
def msg_consumer(channel,method,header,body):
    #消息确认
    channel.basic_ack(delivery_tag=method.delivery_tag)

    if body=="quit":
        #停止消费并退出
        channel.basic_cancel(consumer_tag="hello-consumer")
        channel.stop_consuming()
    else:
        print(body)
    return
#订阅消费者
channel.basic_consume(msg_consumer,queue="hello-queue",consumer_tag="hello-consumer")
#开始消费
channel.start_consuming()

 

RabbitMQ之入门

标签:

原文地址:http://www.cnblogs.com/similarface/p/5895626.html

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