rabbitmq demo

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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值