python之RabbitMQ简单使用

1,简介

RabbitMQ(Rabbit Message Queue)是流行的开源消息队列系统,用erlang语言开发。
 
1.1关键词说明:
Broker:消息队列服务器实体。
Exchange:消息交换机,它指定消息按什么规则,路由到哪个队列。
Queue:消息队列载体,每个消息都会被投入到一个或多个队列。
Binding:绑定,它的作用就是把exchange和queue按照路由规则绑定起来。
Routing Key:路由关键字,exchange根据这个关键字进行消息投递。
vhost:虚拟主机,一个broker里可以开设多个vhost,用作不同用户的权限分离。
producer:消息生产者,就是投递消息的程序。
consumer:消息消费者,就是接受消息的程序。
channel:消息通道,在客户端的每个连接里,可建立多个channel,每个channel代表一个会话任务。
 
1.2消息队列运行机制:
(1)客户端连接到消息队列服务器,打开一个channel。
(2)客户端声明一个exchange,并设置相关属性。
(3)客户端声明一个queue,并设置相关属性。
(4)客户端使用routing key,在exchange和queue之间建立好绑定关系。
(5)客户端投递消息到exchange。
(6)exchange接收到消息后,就根据消息的key和已经设置的binding,将消息投递到一个或多个队列里。
         例如下面的例子中都为首次声明一个队列!!!
 
1.3exchange类型:
1.Direct交换机
特点:依据key进行投递
例如绑定时设置了routing key为”hello”,那么客户端提交的消息,只有设置了key为”hello”的才会投递到队列。
2.Topic交换机
特点:对key模式匹配后进行投递,符号”#”匹配一个或多个词,符号”*”匹配一个词
例如”abc.#”匹配”abc.def.ghi”,”abc.*”只匹配”abc.def”。
3.Fanout交换机
特点:不需要key,采取广播模式,一个消息进来时,投递到与该交换机绑定的所有队列
 
2.构建环境
2.1在windows环境下安装rabbitmq,教程如下:
2.2安装pika模块
python使用rabbitmq服务,可以使用现成的类库pika、txAMQP或者py-amqplib,这里选择了pika。
在命令行中直接使用pip命令:
pip install pika

3.示例测试

实例的内容就是从send.py发送消息到rabbitmq,receive.py从rabbitmq接收send.py发送的信息。

P表示produce,生产者的意思,也可以称为发送者,实例中表现为send.py;

C表示consumer,消费者的意思,也可以称为接收者,实例中表现为receive.py;

中间红色的表示队列的意思,实例中表现为hello队列。

#send
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))# 新建连接,rabbitmq安装在本地则hostname为'localhost'

channel  = connection.channel()#创建通道

# 声明一个队列,生产者和消费者都要声明一个相同的队列,用来防止万一某一方挂了,另一方能正常运行
channel.queue_declare(queue='hello',durable=Ture)#durable是把队列持久化。
#n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',
                      routing_key='hello',# routing_key在使用匿名交换机的时候才需要指定,表示发送到哪个队列
                      body = 'Hello World  yes',
              properties=pika.BasicProperties(delivery_mode=2,))#消息持久化 print("[x] Send 'Hello World !'") connection.close()
#receive

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))## 新建连接,rabbitmq安装在本地则hostname为'localhost'

channel = connection.channel()#创建通道
#You may ask why we declare the queue again ‒ we have already declared it in our previous code.
# We could avoid that if we were sure that the queue already exists. For example if send.py program
#was run before. But we're not yet sure which program to run first. In such cases it's a good
# practice to repeat declaring the queue in both programs.

channel.queue_declare(queue='hello',durable=Ture)# 声明一个队列,生产者和消费者都要声明一个相同的队列,用来防止万一某一方挂了,另一方能正常运行

def callback(ch,method,properties,body):
    print("[x] Received %r"%body)
channel.basic_qos(prefetch_count=1)#没处理完不接受新数据
channel.basic_consume(queue='hello',#去hello队列取消息 on_message_callback=callback,#开始接受数据,有数据就调用callback 方法处理 auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
durable=Ture
原文地址:https://www.cnblogs.com/anhao-world/p/13802571.html