topicProductor.py内容如下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pika
import sys
'''
问题:
实现基于rabbitmq的生产者和消费者,消费者可以支持绑定路由键为notification.*,
则生产者如果绑定的路由键为notification.info,那么生产者发送的消息hello,也可以
被消费者消费。
关键:
1 客户端初始化rabbitmq过程:
1) 建立连接(指定host),获取通道,通道的交换机声明(指定交换机名称和类型)
2) 设定路由键,消息,通道的基本发布(交换机,路由键,消息体)
3) 关闭连接
总结:
建立连接,获取通道->交换机声明->消息发布
输入输出:
服务端启动:
python topicConsumer.py notifications.*
解释:
上述输入参数1:
notifications.*
表示rabbitmq中的topic
客户端启动:
python topicProductor.py notifications.info hello
解释:
上述输入参数1:
notifications.info
表示rabbitmq中的topic
上述输入参数2:
hello
表示此次发送消息的内容
服务端输出:
receive notifications.info: hello
'''
def startProduce(exchangeName, routingKey, exchangeType='topic', host='localhost', message=''):
connection = pika.BlockingConnection(pika.ConnectionParameters(
host=host
))
channel = connection.channel()
channel.exchange_declare(exchange=exchangeName, exchange_type=exchangeType)
channel.basic_publish(exchange=exchangeName,
routing_key=routingKey,
body=message)
print "send: %s: %s" % (routingKey, message)
connection.close()
def process():
if len(sys.argv) < 3:
print "input parameter error, example usage: \n" \
"python topicProductor.py notifications.info hello\n" \
"the first parameter: notifications.info means the topic of rabbitmq\n" \
"the second parameter: hello means the sended content of rabbitmq"
return
exchangeName = 'topicExchange'
routingKey = sys.argv[1]
message = sys.argv[2]
startProduce(exchangeName, routingKey, message=message)
if __name__ == "__main__":
process()
topicConsumer.py如下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pika
import sys
'''
关键:
1服务器rabbitmq初始化过程:
1) 建立连接(指定host),获取通道,通道的交换机声明(指定交换机名称和类型)
2) 获取队列名,设定绑定的key, 通道的队列绑定(交换机,队列名字,路由键)
3) 设置回掉函数(指定通道,方法,属性,消息体)
4) 通道基本消费(回掉函数,队列名,不确认), 通道开始消费
总结:
建立连接,获取通道->交换机声明->绑定队列到交换机->消费消息
'''
def startConsume(exchangeName, routingKey, exchangeType='topic', host='localhost'):
if not host or not exchangeName or not exchangeType or not routingKey:
print "parameters empty, please check"
return
connection = pika.BlockingConnection(pika.ConnectionParameters(
host=host
))
channel = connection.channel()
channel.exchange_declare(exchange=exchangeName,
exchange_type=exchangeType)
result = channel.queue_declare(exclusive=True)
queueName = result.method.queue
channel.queue_bind(exchange=exchangeName,
queue=queueName,
routing_key=routingKey)
channel.basic_consume(callback,
queue=queueName,
no_ack=True)
channel.start_consuming()
def callback(channel , method, properties , body):
print "receive %s: %s" % (method.routing_key , body)
def process():
if len(sys.argv) < 2:
print "input parameter error, example usage: \n" \
"python topicConsumer.py notifications.*\n" \
"the first parameter: notifications.* means the topic of rabbitmq"
return
routingKey = sys.argv[1]
exchangeName = 'topicExchange'
startConsume(exchangeName, routingKey)
if __name__ == "__main__":
process()
参考文章:
[1] http://www.rabbitmq.com/tutorials/tutorial-five-python.html