RabbitMQ hello world带有确认功能的生产者
2017-04-17 19:19
459 查看
publish后加了确认过程,保证消息发布成功。
1. 生产者
代码如下:
2. 消费者
3. 运行RabbitMQ
4. 运行程序
运行生产者:
运行消费者:
publish成功后会打印确认消息。
1. 生产者
代码如下:
#!/usr/bin/env python # -*- coding: UTF-8 -*- import pika import sys from pika import spec credentials = pika.PlainCredentials("guest", "guest") conn_params = pika.ConnectionParameters("localhost", credentials = credentials) #建立到服务器的连接 conn_broker = pika.BlockingConnection(conn_params) #获得信道 channel = conn_broker.channel() #信道设置为confirm模式 channel.confirm_delivery() #声明交换器 channel.exchange_declare(exchange="hello-exchange", type = "direct", passive=False, durable = True, auto_delete = False) msg = sys.argv[1] msg_props = pika.BasicProperties() #纯文本消息 msg_props.content_type = "text/plain" msg_ids = [] #发布消息 ack = channel.basic_publish(body = msg, exchange = "hello-exchange", properties = msg_props, routing_key = "hola") if ack == True: print "消息成功发到RabbitMQ" else: print "消息未发到RabbitMQ" #ID添加到追踪列表中 msg_ids.append(len(msg_ids) + 1) channel.close()
2. 消费者
#!/user/bin/env python # -*- coding: UTF-8 -*- 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") #队列交换器绑定 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 #订阅 channel.basic_consume(msg_consumer, queue = "hello-queue", consumer_tag = "hello-consumer") #消费 channel.start_consuming()
3. 运行RabbitMQ
rabbitmq-server &
4. 运行程序
运行生产者:
python hello_world_producer.py
运行消费者:
python hello_world_consumer.py
publish成功后会打印确认消息。
相关文章推荐
- RabbitMQ HelloWorld
- RabbitMQ Hello World
- RabbitMQ Hello World
- rabbitMQ HelloWorld
- Spring Rabbitmq HelloWorld实例
- RabbitMQ实例教程:Hello RabbitMQ World之Java实现
- 三、rabbitMQ helloWorld入门程序
- 02-RabbitMQ Hello World Spring使用
- HelloWorld RabbitMQ
- rabbitmq helloworld程序异常
- RabbitMQ Java "Hello World" 点对点模式
- RabbitMQ学习(2) --RabbitMQ HelloWorld(Python)
- RabbitMQ hello world示例
- rabbitmq Introduction one "hello world"
- MOM初窥:AcitveMQ HelloWorld
- 用php编写一个函数实现 以下功能:字符串hello_world转换成为HelloWorld, get_field_by_id转换成为GetFieldById
- RabbitMQ ACK 消息确认机制
- rabbitmq publisher(生产者)注意的几个点
- RabbitMQ hello word (python)
- ActiveMQ HelloWorld入门