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

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值