|
RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。它遵循Mozilla Public License开源协议。
MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。
1. RabbitMQ安装配置
1.1 安装epel源
# 安装配置epel源
rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
# 安装erlang
yum -y install erlang
# 安装RabbitMQ
yum -y install rabbitmq-server
PS:系统环境为CentOS_6.8_x64
1.2 启动服务
/etc/init.d/rabbitmq start
1.3 安装API
pip3 install pika
2.Python使用API操作RabbitMQ
生产者
# 导入模块
import pika
# RabbitMQ连接,固定格式
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.101.11'))
channel = connection.channel()
# 队列名称
channel.queue_declare(queue='hello')
# 发发布任务
channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
print(" [x] Sent 'Hello World!")
# 终止任务
connection.close()
消费者
# 导入pika模块(API)
import pika
# RabbitMQ连接,固定格式
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.101.11'))
channel = connection.channel()
# 队列名称
channel.queue_declare(queue='hello')
# 定义方法,当接收生产者的信息时,输出接收内容
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
# 接收消息,执行callback方法处理接收到的信息
channel.basic_consume(callback, queue='hello', no_ack=True)
# 输出系统消息
print('
Waiting for messages. To exit press CTRL+C')
# 运行任务
channel.start_consuming()
3. 消息不丢失
3.1 消息不丢失no_ack=False(客户端)
举例:取出消息处理,处理消息时宕机,消息丢失
no-ack = False,如果消费者遇到情况(its channel is closed, connection is closed, or TCP connection is lost)挂掉了,那么,RabbitMQ会重新将该任务添加到队列中。
# 消息不丢失no_ack=False(客户端)
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='192.168.101.11'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
# 测试时在OK输出前结束任务,模拟中断,重新运行程序后继续接收消息
import time
time.sleep(10)
print('ok')
# 应答,回复生产者确认,如未执行中断,任务将重新放回队列等待处理
ch.basic_ack(delivery_tag = method.delivery_tag)
# 消息不丢失必须参数,no_ack=False
channel.basic_consume(callback,queue='hello',no_ack=False)
print('
Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
3.2 消息不丢失durable
生产者
#!/usr/bin/env python
#-*-coding:utf-8-*-
# 导入模块
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.101.11'))
channel = connection.channel()
# 消息队列持久化durable=True
channel.queue_declare(queue='hello', durable=True)
#
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!666',
# 消息持久化delivery_mode=2,保证服务端数据不丢失
properties=pika.BasicProperties(
delivery_mode=2,
))
print(" [x] Sent 'Hello World!'")
connection.close()
消费者
# 消息不丢失no_ack=False+队列持久化(客户端)
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='192.168.101.11'))
channel = connection.channel()
# 队列持久化durable=True
channel.queue_declare(queue='hello', durable=True)
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
# 测试时在OK输出前结束任务,模拟中断,重新运行程序后继续接收消息
import time
time.sleep(10)
print('ok')
# 应答,回复生产者确认,如未执行中断,任务将重新放回队列等待处理
ch.basic_ack(delivery_tag = method.delivery_tag)
# 消息不丢失必须参数,no_ack=False
channel.basic_consume(callback,queue='hello',no_ack=False)
print('
Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
4. 消息获取顺序
默认消息队列里的数据是按照顺序被消费者拿走,例如:消费者1 去队列中获取 奇数 序列的任务,消费者1去队列中获取 偶数 序列的任务。
channel.basic_qos(prefetch_count=1) 表示谁来谁取,不再按照奇偶数排列
5. 发布订阅 exchange type = fanout
发布订阅和简单的消息队列区别在于,发布订阅会将消息发送给所有的订阅者,而消息队列中的数据被消费一次便消失。所以,RabbitMQ实现发布和订阅时,会为每一个订阅者创建一个队列,而发布者发布消息时,会将消息放置在所有相关队列中。
exchange type = fanout
发布者
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.101.11'))
channel = connection.channel()
channel.exchange_declare(exchange='logs_fanout', type='fanout')
# 消息
message = '123'
# 发布消息
channel.basic_publish(exchange='logs_fanout', routing_key='', body=message)
print(" [x] Sent %r" % message)
# 连接关闭
connection.close()
消费者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.101.11'))
channel = connection.channel()
channel.exchange_declare(exchange='logs_fanout', type='fanout')
# 随机创建队列
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
# 绑定队列
channel.queue_bind(exchange='logs_fanout', 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(callback, queue=queue_name, no_ack=True)
channel.start_consuming()
6. 关键字发送 exchange type = direct
exchange type = direct
之前事例,发送消息时明确指定某个队列并向其中发送消息,RabbitMQ还支持根据关键字发送,即:队列绑定关键字,发送者将数据根据关键字发送到消息exchange,exchange根据 关键字 判定应该将数据发送至指定队列。
发布者
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='192.168.101.11'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
type='direct')
# 关键字
severity = sys.argv[1] if len(sys.argv) > 1 else 'error'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
# routing_key 关键字
channel.basic_publish(exchange='direct_logs',
routing_key=severity,
body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()
消费者['error', 'info', 'warning']
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.101.11'))
channel = connection.channel()
# type='direct'
channel.exchange_declare(exchange='direct_logs', type='direct')
# 随机创建队列
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
severities = ['error', 'info', 'warning']
# severities = sys.argv[1:]
# if not severities:
# sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
# sys.exit(1)
for severity in severities:
channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key=severity)
print('
Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(callback, queue=queue_name, no_ack=True)
channel.start_consuming()
消费者['error', ]
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='192.168.101.11'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
type='direct')
# 随机创建队列
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
severities = ['error',]
# severities = sys.argv[1:]
# if not severities:
# sys.stderr.write("Usage: %s [error]\n" % sys.argv[0])
# sys.exit(1)
for severity in severities:
channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key=severity)
print('
Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
7. 模糊匹配exchange type = topic
exchange type = topic
在topic类型下,可以让队列绑定几个模糊的关键字,之后发送者将数据发送到exchange,exchange将传入”路由值“和 ”关键字“进行匹配,匹配成功,则将数据发送到指定队列。
- # 表示可以匹配 0 个 或 多个 单词
- * 表示只能匹配 一个 单词
发送者路由值 队列中
old.boy.python old.* -- 不匹配
old.boy.python old.# -- 匹配 |
|