消息队列MQ
一、消息队列概述
MQ(Message Queue)消息队列,是基础数据结构中“先进先出”的一种数据结构。指把要传输的数据(消息)放在队列中,用队列机制来实现消息传递——生产者产生消息并把消息放入队列,然后由消费者去处理。消费者可以到指定队列拉取消息,或者订阅相应的队列,由MQ服务端给其推送消息。主要解决应用解耦,异步消息,消息分发(发布订阅:观察者模式),流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构。目前使用较多的消息队列有ActiveMQ,RabbitMQ,ZeroMQ,Kafka,MetaMQ,RocketMQ。

二、消息队列应用场景
MQ解决的问题主要有有以下四种:
1.应用解耦 2.流量消峰 3.消息分发(发布订阅:观察者模式) 4.异步消息(celery就是对消息队列的封装)
应用解耦:
一个业务需要多个模块共同实现,或者一条消息有多个系统需要对应处理,只需要主业务完成以后,发送一条MQ,其余模块消费MQ消息,即可实现业务,降低模块之间的耦合。

流量削峰:
消息分发:
多个服务队数据感兴趣,只需监听同一类消息即可处理。


异步:
三、RabbitMQ
RabbitMQ官网:https://rabbitmq.com/
目前使用较多的消息队列有ActiveMQ,RabbitMQ,ZeroMQ,Kafka,MetaMQ,RocketMQ,这里我们主要介绍RabbitMQ。
1.安装
1.1 原生安装
需要先安装epel扩展源:https://dl.fedoraproject.org/pub/epel/,在其中找到对应的版本下载安装即可,如下:
wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm
下载erlang
yum -y install erlang
安装并启动 rabbitmq
yum -y install rabbitmq-server
systemctl start rabbitmq-server
1.2 docker 上安装
直接在docker上拉取镜像即可,这里我们选择 rabbitmq:management 版本的,因为该版本带有web管理界面,无需自己去配置
docker pull rabbitmq:management
启动容器,映射端口,并设置密码
docker run -di --name rabbitmq -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin -p 15672:15672 -p 5672:5672 rabbitmq:management
参数详解:
5672:是rabbitmq的默认端口
15672:web管理界面的端口


2.创建用户
如果是原生安装模式直接输入如下即可:
rabbitmqctl add_user yessir 123 # 如果是通过docker容器启动的,需要先进入docker容器再执行上面这句命令(docker exec -it 容器id bash)
3.分配用户权限
如果是原生安装模式直接输入如下即可:
rabbitmqctl set_user_tags yessir administrator # 添加用户标签 rabbitmqctl set_permissions -p "/" yessir ".*" ".*" ".*" # 添加用户权限 # 如果是通过docker容器启动的,需要先进入docker容器再执行上面的两句命令(docker exec -it 容器id bash)
RabbitMQ基本使用
简单使用

生产者发送一个消息,放入队列中
# 生产者.py import pika # 生成连接对象,没有密码的情况下,直接得到connection对象 # connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200')) # 有用户名密码的情况 credentials = pika.PlainCredentials("admin","admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200',credentials=credentials)) # 通过连接对象生成channel channel = connection.channel() # 声明一个队列 channel.queue_declare(queue='hello') # 指定队列名字 # 生产者向队列中放一条消息 channel.basic_publish(exchange='', routing_key='hello', body='yessir hhh nb') print(" Sent 'Hello World!'") # 关闭连接 connection.close()
消费者可以从消息队列中拿到生产者发送的数据,并且夯住,等待,如果消息队列里有数据,就会直接取出来
# 消费者.py
import pika, sys, os def main(): # connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.0.0.200')) credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True) channel.start_consuming() if __name__ == '__main__': main()


在web管理界面,可以看到消息队列的信息情况

# 生产者.py import pika # 拿到连接对象 # connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200')) # 有用户名密码的情况 credentials = pika.PlainCredentials("admin","admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200',credentials=credentials)) # 拿到channel对象 channel = connection.channel() # 声明一个队列 channel.queue_declare(queue='yessir') # 指定队列名字 # 生产者向队列中放一条消息 channel.basic_publish(exchange='', routing_key='yessir', body='yessir is nb') print(" 发送成功") # 关闭连接 connection.close()
设置了basic_consume中的参数auto_ack=True后,生产者向消息队列中发送数据,消费者接收数据后,会自动确认并删除数据,而此时数据可能还没有处理完毕。
设置 auto_ack=False 不会自动确认消息,添加了 ch.basic_ack(delivery_tag=method.delivery_tag) 后,会等消息处理完后,再发送确认并删除数据。
# 消费者.py import pika, sys, os def main(): # connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.0.0.200')) credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.queue_declare(queue='yessir') def callback(ch, method, properties, body): print(" [x] Received %r" % body) # 真正的消息处理完了,再发确认 ch.basic_ack(delivery_tag=method.delivery_tag) # 不会自动回复确认消息, # auto_ack=True,队列收到确认,就会自动把消费过的消息删除 channel.basic_consume(queue='yessir', on_message_callback=callback, auto_ack=False) channel.start_consuming() if __name__ == '__main__': main()

持久化机制
在生产者的队列申明中添加 durable=True 参数,可以使队列持久化,在 basic_publish 中添加参数,设置消息持久化,这样我们重启 rabbitmq 后,还能看到队列以及队列中的消息
# 生产者.py import pika # 拿到连接对象 # connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200')) # 有用户名密码的情况 credentials = pika.PlainCredentials("admin","admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200',credentials=credentials)) # 拿到channel对象 channel = connection.channel() # 声明一个队列 channel.queue_declare(queue='yessir_new',durable=True) # 设置durable=True让队列持久化 # 生产者向队列中放一条消息 channel.basic_publish(exchange='', routing_key='yessir_new', body='yessir very nb', properties=pika.BasicProperties( delivery_mode=2, # 设置消息持久化 ) ) print(" yessir very nb'") # 关闭连接 connection.close()
消费者
# 消费者.py import pika, sys, os def main(): # connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.0.0.200')) credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.queue_declare(queue='yessir_new',durable=True) def callback(ch, method, properties, body): print(" [x] Received %r" % body) # 真正的消息处理完了,再发确认 ch.basic_ack(delivery_tag=method.delivery_tag) ## 不会自动回复确认消息, ## auto_ack=True,队列收到确认,就会自动把消费过的消息删除 channel.basic_consume(queue='yessir_new', on_message_callback=callback, auto_ack=False) channel.start_consuming() if __name__ == '__main__': main()
闲置消费
如果我们启动两个消费者,当生产者发送数据的时候,会由两个消费者轮流接收,但是这样并不合理,如果第1个消费者接收数据需要5分钟,而第二个消费者只要1分钟,当第二个消费者消费完数据,又轮到第1个消费者,但是第1个消费者的数据还没消费完,这样,就会导致某个数据必须给第1个消费者,造成数据积压,所以我们可以设置参数,谁闲置谁就能消费数据,如下:

channel.basic_qos(prefetch_count=1) # 添加这一句话 谁闲置谁获取,没必要按照顺序一个一个来
生产者
# 生产者.py import pika # 拿到连接对象 # connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200')) # 有用户名密码的情况 credentials = pika.PlainCredentials("admin","admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200',credentials=credentials)) # 拿到channel对象 channel = connection.channel() # 声明一个队列 channel.queue_declare(queue='yessir') # 指定队列名字 # 生产者向队列中放一条消息 channel.basic_publish(exchange='', routing_key='yessir', body='yessir is nb') print(" 发送成功") # 关闭连接 connection.close()
消费者
消费者1,我们这里给他设置sleep 50秒,所以当他sleep期间,队列中只要有数据,都会由消费者2接收
# 消费者1.py import pika, sys, os def main(): # connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.0.0.200')) credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.queue_declare(queue='yessir') def callback(ch, method, properties, body): import time time.sleep(50) print(" [x] Received %r" % body) # 真正的消息处理完了,再发确认 ch.basic_ack(delivery_tag=method.delivery_tag) # 不会自动回复确认消息, # auto_ack=True,队列收到确认,就会自动把消费过的消息删除 channel.basic_qos(prefetch_count=1) # 就只有这一句话 谁闲置谁获取,没必要按照顺序一个一个来 channel.basic_consume(queue='yessir', on_message_callback=callback, auto_ack=False) channel.start_consuming() if __name__ == '__main__': main()
消费者2
import pika, sys, os def main(): # connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.0.0.200')) credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.queue_declare(queue='yessir') def callback(ch, method, properties, body): print(" [x] Received %r" % body) # 真正的消息处理完了,再发确认 ch.basic_ack(delivery_tag=method.delivery_tag) # 不会自动回复确认消息, # auto_ack=True,队列收到确认,就会自动把消费过的消息删除 channel.basic_qos(prefetch_count=1) # 就只有这一句话 谁闲置谁获取,没必要按照顺序一个一个来 channel.basic_consume(queue='yessir', on_message_callback=callback, auto_ack=False) channel.start_consuming() if __name__ == '__main__': main()
发布订阅
向多个消费者传递一条消息。这种模式被称为“发布/订阅”,即发布一条消息,多个消费者都能接收到。如下图所示:生产者发送一条数据,通过交换机分发出多条队列,每个消费者都可以从队列中获取数据。
发布者发送一条数据(需要在队列申明中设置 exchange_type='fanout')
# 发布者.py import pika credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() # 声明队列没有指定名字,指定了exchange channel.exchange_declare(exchange='logs', exchange_type='fanout') message = "info: Hello World!" channel.basic_publish(exchange='logs', routing_key='', body=message) print(" [x] Sent %r" % message) connection.close()
多个订阅者都能接收到消息(需要在队列申明中设置 exchange_type='fanout')
# 订阅者.py
# 订阅者(启动多次,会创建出多个队列,都绑定到了同一个exchange上) import pika credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.exchange_declare(exchange='logs', exchange_type='fanout') result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue print(queue_name) channel.queue_bind(exchange='logs', queue=queue_name) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r" % body) channel.basic_consume( queue=queue_name, on_message_callback=callback, auto_ack=True) channel.start_consuming()

应用场景:比如微博,某明星发送一条微博,他的关注者全都能看到他发送的微博
发布订阅高级用法之Routing(按关键字匹配)
生产者发布一条消息,指定只有绑定某个关键字的订阅者才能接收到
例:
发布者:
订阅者1只绑定监听了‘nb’,而订阅者2同时绑定监听了‘nb’、‘bnb’两个关键字
如果发布者的 routing_key 指定 ‘nb’,那两个订阅者都能接收到消息
如果发布者的 routing_key 指定 ‘bnb’,那只有订阅者2能接收到消息,而订阅者1接收不到
# 发布者.py import pika credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() # 声明队列没有指定名字,指定了exchange channel.exchange_declare(exchange='ys123', exchange_type='direct') # 指定exchange_type='direct' message = "info: asdfasdfasdfsadfasdf World!" channel.basic_publish(exchange='ys123', routing_key='nb', body=message) # 指定routing_key='xxx'的才能收到 print(" [x] Sent %r" % message) connection.close()
订阅者1:
订阅者1只绑定监听了‘nb’
# 订阅者1 import pika credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.exchange_declare(exchange='ys123', exchange_type='direct') result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue print(queue_name) # 绑定exchanges,并且指定routing_key关键字 channel.queue_bind(exchange='ys123', queue=queue_name,routing_key='nb') print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r" % body) channel.basic_consume( queue=queue_name, on_message_callback=callback, auto_ack=True) channel.start_consuming() channel.start_consuming()
订阅者2:
订阅者2同时绑定监听了‘nb’、‘bnb’两个关键字
# 订阅者2 import pika credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.exchange_declare(exchange='ys123', exchange_type='direct') result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue print(queue_name) # 绑定exchanges,并且指定routing_key关键字 channel.queue_bind(exchange='ys123', queue=queue_name,routing_key='nb') channel.queue_bind(exchange='ys123', queue=queue_name,routing_key='bnb') print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r" % body) channel.basic_consume( queue=queue_name, on_message_callback=callback, auto_ack=True) channel.start_consuming() channel.start_consuming()
当发布者指定关注‘nb’关键字的能接收到时,订阅者1、2都能接收到消息,如下图:

当发布者指定关注‘bnb’关键字的能接收到时,因为只有订阅者2关注了‘bnb’,所以订阅者2能接收到消息,而订阅者1则无法接收,如下图:

发布订阅高级用法之Routing(模糊匹配)
# 表示后面可以跟任意字符
*表示后面只能跟一个单词
发布者:
# 发布者.py import pika credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() # 声明队列没有指定名字,指定了exchange channel.exchange_declare(exchange='m3', exchange_type='topic') message = "info: asdfasdfasdfsadfasdf World!" channel.basic_publish(exchange='m3', routing_key='ys.dd', body=message) print(" [x] Sent %r" % message) connection.close()
订阅者1
# 订阅者1 import pika credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.exchange_declare(exchange='m3', exchange_type='topic') result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue print(queue_name) channel.queue_bind(exchange='m3', queue=queue_name,routing_key='ys.*') print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r" % body) channel.basic_consume( queue=queue_name, on_message_callback=callback, auto_ack=True) channel.start_consuming()
订阅者2
# 订阅者2 import pika credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) channel = connection.channel() channel.exchange_declare(exchange='m3', exchange_type='topic') result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue print(queue_name) channel.queue_bind(exchange='m3', queue=queue_name,routing_key='ys.#') print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r" % body) channel.basic_consume( queue=queue_name, on_message_callback=callback, auto_ack=True) channel.start_consuming()

浙公网安备 33010602011771号