rabbitmq task.py
# coding: utf-8
import pika
import sys
import time
from pika import spec
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
#Turn on Confirm mode in the channel
channel.confirm_delivery()
#设置队列优先级,可在后台管理网站中查看
priority_queue = {"x-max-priority":20}
#durable=True为queue持久化
channel.queue_declare(queue='new_priority',durable=True,arguments=priority_queue)
message = ' '.join(sys.argv[1:]) or "hello world"
#此处的message的priority为消息优先,properties为message持久化
if (channel.basic_publish(exchange='',
routing_key='new_priority',
body=message, properties=pika.BasicProperties(content_type="text/plain",delivery_mode=2,priority=11))):
print "Message publish was confirmed"
else:
print "Message could not be confirmed"
print " [x] Sent %r" % (message,)
connection.close()
rabbitmqreceive.py
# coding: utf-8
import time
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
priority_queue = {"x-max-priority":20}
channel.queue_declare(queue='priority',durable=True,arguments=priority_queue)
def callback(ch,method,properties,body):
print " [x] Received %r" % (body,)
time.sleep(body.count('.'))
print "add sleep function, the program start sleep 10 seconds !"
time.sleep(10)
print " [x] done"
#添加ack机制
ch.basic_ack(delivery_tag=method.delivery_tag)
#channel.basic_consume(callback,queue='hello',no_ack=True)
channel.basic_consume(callback,queue='priority')
channel.start_consuming()
附加一个API:
#清除某个queue中的message
channel.queue_purge(queue='priority')