首页 > 代码库 > RabbitMQ之入门

RabbitMQ之入门

生成者:

#coding:utf-8__author__ = similarfaceimport pika,sys#连接RabbitMQcredentials = 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__ = similarfaceimport 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之入门