uit**1. 生产者**
生产者需要完成以下任务:
(1)连接到RabbitMQ
(2) 获取信道
(3) 声明交换器
(4) 创建消息
(5)发布消息
(6)关闭信道
(7)关闭连接
编写生产者文件hello_world_producer.py, 代码以python书写。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pika
import sys
credentials = pika.PlainCredentials("guest", "guest")
conn_params = pika.ConnectionParameters("localhost", credentials = credentials)
#建立到服务器的连接
conn_broker = pika.BlockingConnection(conn_params)
#获得信道
channel = conn_broker.channel()
#声明交换器
channel.exchange_declare(exchange="hello-exchange", type = "direct", passive=False, durable = True, auto_delete = False)
msg = sys.argv[1]
msg_props = pika.BasicProperties()
#纯文本消息
msg_props.content_type = "text/plain"
#发布消息
channel.basic_publish(body = msg, exchange = "hello-exchange", properties = msg_props, routing_key = "hola")
2. 消费者需要完成以下任务
(1) 连接到RabbitMQ
(2) 获得信道
(3) 声明交换器
(4) 声明队列
(5)把队列和交换器绑定起来
(6)消费消息
(7)关闭信道
(8)关闭连接
消费者文件hello_world_consumer.py
#!/user/bin/env python
# -*- coding: UTF-8 -*-
import pika
credentials = pika.PlainCredentials("guest", "guest")
#建立到服务器的连接
conn_params = pika.ConnectionParameters("localhost", credentials = credentials)
conn_broker = pika.BlockingConnection(conn_params)
#获得信道
channel = conn_broker.channel()
#声明交换器
channel.exchange_declare(exchange = "hello-exchange", type = "direct", passive = False, durable = True, auto_delete = False)
#声明队列
channel.queue_declare(queue = "hello-queue")
#队列交换器绑定
channel.queue_bind(queue = "hello-queue", exchange = "hello-exchange", routing_key = "hola")
def msg_consumer(channel, method, header, body):
"消息处理函数"
#消息确认
channel.basic_ack(delivery_tag = method.delivery_tag)
if body == "quit":
#停止消费并退出
channel.basic_cancel(consumer_tag = "hello-consumer")
channel.stop_consuming()
else:
print body
#订阅
channel.basic_consume(msg_consumer, queue = "hello-queue", consumer_tag = "hello-consumer")
#消费
channel.start_consuming()
3. 运行RabbitMQ
演示生产者消费者需要确保RabbitMQ在运行中。
rabbitmq-server &
4. 测试程序
运行消费者
python hello_world_consumer.py
运行消费者,并发布消息hello world
python hello_producer.py "hello world"
此时消费者可以接收到消息”hello world”
生产者发送 quit 则消费者退出。