1、publisher端:amqp_publisher_test.py
# -*- coding: utf-8 -*-
from amqplib import client_0_8 as amqp
import sys
import datetime
conn = amqp.Connection(host="xx.xx.xx.43:5672", userid="guest", password="guest", virtual_host="/", insist=True)
chan = conn.channel()
time = sys.argv[1]
now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
count = 1
while now_time < sys.argv[1]:
now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
msg = amqp.Message(str(count))
msg.properties["delivery_mode"] = 2
try:
chan.basic_publish(msg,exchange="sorting_room",routing_key="jason")
count += 1
except:
conn = amqp.Connection(host="xx.xx.xx.43:5672", userid="guest", password="guest", virtual_host="/", insist=False)
chan = conn.channel()
chan.basic_publish(msg,exchange="sorting_room",routing_key="jason")
count += 1
print >> open("43.txt","a+"), count
print count
print 'end'
try:
chan.close()
conn.close()
except Exceptions as msg:
log.msg("rabbitmq connect has a error: %s"% msg, level=log.ERROR)
2、consumer端amqp_consumer.py
# -*- coding: utf-8 -*-
from amqplib import client_0_8 as amqp
conn = amqp.Connection(host="xx.xx.xx.xx:5672", userid="guest", password="guest", virtual_host="/", insist=True)
chan = conn.channel()
chan.queue_declare(queue="po_box", durable=True, exclusive=False, auto_delete=False)
chan.exchange_declare(exchange="sorting_room", type="direct", durable=True, auto_delete=False,)
chan.queue_bind(queue="po_box", exchange="sorting_room", routing_key="jason")
def recv_callback(msg):
print 'Received: ' + msg.body + ' from channel #' + str(msg.channel.channel_id)
print >> open("txt_44.txt","a+"), msg.body
msg.channel.basic_ack(delivery_tag = msg.delivery_tag)
chan.basic_consume(queue='po_box', no_ack=False, callback=recv_callback, consumer_tag="testtag")
while True:
chan.wait()
chan.basic_cancel("testtag")
chan.close()
conn.close()
注:
(1)运行publisher端:python2.7 amqp_publisher_test.py "2013-07-17 18:18:30"
(2)运行consumer端:python2.6 amqp_consumer.py