RabbitMQ之入门

Posted similarface

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RabbitMQ之入门相关的知识,希望对你有一定的参考价值。

生成者:

#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之入门的主要内容,如果未能解决你的问题,请参考以下文章

RabbitMQ之入门

快速入门分布式消息队列之 RabbitMQ(中)

快速入门分布式消息队列之 RabbitMQ(上)

RabbitMQ 入门之基础概念

RabbitMQ入门工作队列

RabbitMQ入门:Hello RabbitMQ 代码实例