​https://www.jianshu.com/p/95a1b33e0555​​​​javascript:void(0)​

import pika

import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

channel = connection.channel()

# durable:server挂了队列仍然存在

channel.queue_declare(queue='task_queue', durable=True)

# 使用默认的交换机发送消息。exchange为空就使用默认的。delivery_mode=2:使消息持久化。和队列名称绑定routing_key

message = ' '.join(sys.argv[1:]) or "Hello World!"

channel.basic_publish(exchange='',

routing_key='task_queue',

body=message,

properties=pika.BasicProperties(

delivery_mode=2,

))

print(" [x] Sent %r" % message)

connection.close()

消费端:

import pika

import time

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)

print(' [*] Waiting for messages. To exit press CTRL+C')

def callback(ch, method, properties, body):

print(" [x] Received %r" % body)

time.sleep(body.count(b'.'))

print(" [x] Done")

# 手动对消息进行确认

ch.basic_ack(delivery_tag=method.delivery_tag)

# basic_consume:这个函数有no_ack参数。该参数默认为false。表示:需要对message进行确认。怎么理解:no设置成false,表示要确认

channel.basic_consume(callback, queue='task_queue')

channel.start_consuming()

说明:

个人觉得rabbitMQ比较好的一点是能够对消费的信息进行反馈,如果消费端的程序运行失败了,还可以重复消费.


懂得,原来世界如此简单!