1.独立进程间的通信(比如不同应用,注意不是多进程的通信)
(1)通过磁盘写入,读出
(2)建立socket
(3)通过broker(中间件代理,到broker也是通过建立的socket)
2.常见的消息队列
RabbitMQ ZeroMQ ActiveMQ kafka(日志系统)
RabbitMq、ActiveMq、ZeroMq、kafka之间的比较:
转载:https://blog.csdn.net/qq853632587/article/details/75009735
RabbitMQ使用(添加用户,虚拟主机等)转载:https://blog.csdn.net/kk185800961/article/details/55214474
3.RabbitMQ简介
rabbitMQ是erlang开发的,在windows上和linux上都要装erlang
openstack 默认用的rabbitmq
概念模型:
4.rabbitMQ简单的使用
如果关闭rabbitMQ服务,数据会丢失,所以要对每一个队列做消息持久化 在producer里加
队列持久化:channel.queue_declare(queue=‘hello’,durable=True)
消息持久化:在chanel.basic_publish{
properties=pika.BasicProperties(delivery_mode=2,) }
使用rabbitmq通信的源码加解析:
消息公平分发
实现消息公平分发代码如下
producer:
'''send端'''
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
channel=connection.channel() # 申明一个管道
# 申明queue
channel.queue_declare(queue='hello',durable=True) # 队列持久化
channel.basic_publish(
exchange='',
routing_key='hello',# queue名字
body='Hello world!',
properties = pika.BasicProperties(
delivery_mode=2 , # 消息持久化
)
)
print("[x] sent 'Hello world!'")
connection.close()
consumer:
注意消费者默认basic_consume中的要给生产者发送“收到消息”的确认信息
no_ack=True # no acknowledgement 消息处理完了之后,不给producer 说
保留no_ack=True 就是不确认 producer 不关心consumer是否处理完消息
一般默认是要确认,且最好不用 no_ack,因为如果consumer断了,producer好把消息作为新消息给下一个queue处理实现消息轮询
要想producer等consumer处理完当前消息再给它发消息的实现:
在consumer 中加入 channerl.basic_qos(prefetch_count=1)
#!/usr/bin/env python
# coding:utf-8
# Author:Yang
'''receive端'''
'''消息公平分发'''
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
channel=connection.channel()
channel.queue_declare(queue='hello',durable=True) # 为什么还要声明?因为不知道消费者和生产者谁先启动,所以要避免出错才声明
def callback(ch,method,properties,body):
print(ch,method,properties)
print(method)
print("[x] Received %r"%body)
ch.basic_ack(delivery_tag=method.delivery_tag) # 手动确认消息
channel.basic_qos(prefetch_count=1) # 告诉producer 等我处理完这一条 再给我发下一条 实现消息公平分发(可能因为这个配置不高的消费者处理不完那么多消息而堆积)
channel.basic_consume( # 消费消息
callback, # 如果收到消息,就调用CALLBACK函数来处理消息 (回调函数)
queue='hello'
# no_ack=True # no acknowledgement 消息处理完了之后,不给producer 说
# 保留no_ack=True 就是不确认 producer 不关心consumer是否处理完消息
# 一般默认是要确认,且最好不用 no_ack,因为如果consumer断了,producer好把消息作为新消息给下一个queue处理实现消息轮询
)
print('[*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() # 开始收(一直收)
如果要外网能连接rabbitMQ,开头写法为
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost',5672,'/',credentials))
注意:guest只能本地访问
5.RabbitMq 消息的订阅、发布
(1)fanout:所有bind到此exchange的queue都可以接收消息
(2)direct:通过routingKey和exchange决定的那个唯一的queue可以接收消息
(3)topic:所有复合routingKsy(此时可以是一个表达式)的routingKey所bind的queue可以接收消息
(4)headers:通过headers来绝对把消息发给哪些queue(很少用)
rabbitmq与activemq的消息订阅发布不同点:
activemq最常用的topic消息订阅发布,发布者发布信息到topic ,消费者绑定topic并从topic拿信息
rabbitmq的topic 是更细致的消息过滤,比如 发布者发布 mysql.info 消费者topic为mysql.*可以收到这个信息
(1)fanout订阅广播:
为什么叫广播? 因为如果consumer没有运行 是收不到producer的消息的,就像广播,没有打开收音机就听不到
producer:
'''fanout 订阅广播producer'''
import sys
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel=connection.channel()
channel.exchange_declare(exchange='logs', # 声明exchange类型
exchange_type='fanout')
# 在producer端不用制定队列名字 因为queue是绑定到exhcange上的,且queue的名字是随机的
message="info:hello world!"
channel.basic_publish(
exchange='logs',
routing_key='',# 不用制定queue的名字
body=message
)
print("[x] Sent %r"%message)
connection.close()
consumer:
'''fanout订阅广播consumer'''
import pika
connection=pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel=connection.channel()
channel.exchange_declare(exchange='logs', # 声明 exchange类型
exchange_type='fanout')
result = channel.queue_declare(exclusive=True) # exclusive(排他)参数是指不用指定queue的名字,rabbit会随机分配一个名字,在消费者断开后,自动将queue删除
queue_name=result.method.queue # 拿到queue的名字
print('random queue_name',queue_name)
channel.queue_bind(exchange='logs', # 将queue绑定exchange
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()
# 如果consumer没有运行 是收不到producer的消息的,就像广播,没有打开收音机就听不到
(2)direct 有选择消息接收
producer:
发送消息,并带上该消息的类型
'''有选择接收 direct producer端'''
import sys
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
exchange_type='direct')
severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
# argv[1]表示第一个参数,如果没有参数 则默认发送'info':helloworld
# 如果有一个参数以上,第一个参数是发送的类型 例如"error",第二个参数到后面都是message
message=''.join(sys.argv[2:]) or 'hello world'
channel.basic_publish(
exchange='direct_logs',
routing_key=severity,
body=message
)
print("[x] sent %r:%r"%(severity,message))
connection.close()
# producer 发送消息 并带上该消息的类型
consumer:
consumer 定义从queue收到消息的类型,然后只收该类型消息,消息类型是一个list
'''有选择接收 direct consumer端'''
import sys
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
exchange_type='direct')
result=channel.queue_declare(exclusive=True) # 随机queue
queue_name=result.method.queue
severities=sys.argv[1:] # 设置的运行参数 去除掉py文件名本身 (发送命令格式例如 python direct_consumer.py waring error)
# severities就是[warning,error]
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()
# consumer 定义从queue收到消息的类型,然后只收该类型消息,消息类型是一个list
(3)topic 更细致的消息过滤
“#” 号收所有
*.mysql mysql在第二个 msyql. * mysql开头 只有两个
producer:
'''更细致的消息过滤 topic producer'''
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
exchange_type='topic')
routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(exchange='topic_logs',
routing_key=routing_key,
body=message)
print(" [x] Sent %r:%r" % (routing_key, message))
connection.close()
consumer:
'''更细致的消息过滤 topic consumer'''
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
exchange_type='topic')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
binding_keys = sys.argv[1:]
if not binding_keys:
sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
sys.exit(1)
for binding_key in binding_keys:
channel.queue_bind(exchange='topic_logs',
queue=queue_name,
routing_key=binding_key)
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()
# # 号收所有
# *.mysql mysql在第二个
# msyql.* mysql开头 只有两个
6.RPC服务
remote procedure call(远程程序调用) ----RPC服务 RPC
服务就是本地发送执行指令到远程主机,发送到远程,远程主机返回结果给本地主机 既是消费者又是生产者
7.RabbitMQ实现RPC服务
整个rpc服务的流程为:
先启动server 再启动client
(1) server 声明 rpc_queue 往里面收要处理的数据,client通过rpc_queue发数据,包含 server处理完数据要返回结果使用的一个随机queue的指针(reply_to)和 一个随机生成的corr_id
(2) server 从rpc_queue拿到数据 进行处理,处理完后调用回调函数,通过 随机的queue 发送带有 corr_id 和 结果的消息传给client
(3) client 收到消息 调用回调函数 展示结果
注意:生成corr_id的作用在于,确保返回的数据是这次调用远程函数的结果,比如一个函数处理5分钟,一个函数处理2分钟,处理的快的先返回了,为了
防止这种情况,需要加入corr_id来确认是否为函数调用的正确结果
rpc_client.py
''' rpc client rpc服务的客户端'''
import pika
import uuid
class FibonacciRpcClient(object):
def __init__(self):
self.credentials = pika.PlainCredentials('guest', 'guest')
self.connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672, '/', self.credentials))
self.channel = self.connection.channel()
result = self.channel.queue_declare(exclusive=True) # server端执行完的结果 用一个随机生成的queue接收(就是callback_queue)
self.callback_queue = result.method.queue
self.channel.basic_consume(self.on_response, no_ack=True,# 用来收server端执行的结果 on_response 是回调函数,收到消息则执行
queue=self.callback_queue)
def on_response(self, ch, method, props, body):# 回调函数
if self.corr_id == props.correlation_id: # 如果client端生成的随机id与server端返回的随机id一致 则将返回的消息赋给body
self.response = body
def call(self, n):
self.response = None
self.corr_id = str(uuid.uuid4()) # uuid模块,调用uuid.uuid4() 可以生成一个唯一的随机id
self.channel.basic_publish(exchange='',
routing_key='rpc_queue', # 发送数据的时候使用rpc_queue
properties=pika.BasicProperties(
reply_to=self.callback_queue, # props里制定了server端执行完要返回结果通过的queue为上面随机生成的queue
correlation_id=self.corr_id, # 带上生成的随机id为参数
),
body=n)
while self.response is None:
self.connection.process_data_events() # 这句是死循环接受server返回的信息,没有结果不用一直等待,是表示使用非阻塞式的connection.start_consuming
print("no msg..")
return self.response.decode()
fibonacci_rpc = FibonacciRpcClient()
print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call('a')
print(" [.] Got %r" % response)
rpc_server.py
''' rpc server rpc服务的服务端'''
import pika
import time
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost',5672,'/',credentials))
channel = connection.channel()
channel.queue_declare(queue='rpc_queue') # 同样声明 从rpc_queue里收到要server端处理的数据
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
def on_request(ch, method, props, body): # 回调函数 收到client端发来的信息进行处理,处理完之后时调用就给client发结果了
n=body.decode()
print(" [.] fib(%s)" % n)
response = n
ch.basic_publish(exchange='',
routing_key=props.reply_to, # 获取client传来的props里定义的返回结果使用的queue (client props属性里reply_to的一个随机queue)
properties=pika.BasicProperties(correlation_id= props.correlation_id), # 获取client里传来props里的随机id
body=response)
ch.basic_ack(delivery_tag=method.delivery_tag) # server端处理完消息要给client发一个确认
channel.basic_consume(on_request, queue='rpc_queue')
print(" [x] Awaiting RPC requests")
channel.start_consuming()