您的位置:首页 > 其它

RabbitMQ hello world带有确认功能的生产者

2017-04-17 19:19 459 查看
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成功后会打印确认消息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: