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成功后会打印确认消息。