首页 > 代码库 > RabbitMQ之入门
RabbitMQ之入门
生成者:
#coding:utf-8__author__ = ‘similarface‘import 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__ = ‘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之入门
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。