tags:
categories:
rabbitmqct1.bat list_queues #查看队列
#product.py服务器生产者
import pika
'''
连接参数 host,port(默认5672),virtual_host,credentials(验证)
credentials = pika.PlainCredentials('shampoo', '123456') # mq用户名和密码验证
虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
'''
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明queue(给队列起名)
channel.queue_declare(queue='hello')
# n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
# 基本发送
channel.basic_publish(exchange='', # 图中的X,不用深究。知道默认为''就行
routing_key='hello', # queue名字
body='Hello World!') # 发送的内容
print("消息发送完毕")
connection.close()
# consumer.py 客户端消费者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 这里在声明一次hello的原因。如果消费者先运行,hello生产者还不存在就会报错。
# 如果确定服务器端先启动,队列名确定叫hello。下面也可以不写(推荐写上呀!!!兄弟)
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
'''
:param ch: 管道的内存对象
:param method:
:param properties:
:param body:
:return:
'''
import time
print("开始")
time.sleep(10)
print("Received %r" % body)
ch.basic_ack(delivery_tag=method.delivery_tag)
# 消费消息,如果收到消息就调用callback处理消息。从hello队列中收消息。
# auto_ack 自动确认,消息处理完给服务器发消息
channel.basic_consume('hello', callback, True)
print('等待接收消息,关闭按CTRL+C')
channel.start_consuming()
# 创建账号
rabbitmqctl add_user admin 123456
# 设置用户角色
rabbitmqctl set_user_tags admin administrator
# 设置用户权限
rabbitmqctl set_permissions -p "/“oldlu” .""."".*"
# 设置完成后可以查看当前用户和角色(需要开启服务)
rabbitmqctl list_users
# 客户端最多存一条
channel.basic_qos(prefetch_count=1)
MQ默认建立的是临时 queue 和 exchange,如果不声明持久化,一旦 rabbitmq 挂掉,queue、exchange 将会全部丢失。所以我们一般在创建 queue 或者 exchange 的时候会声明持久化。客户端和服务器端都需要设置。
# 声明消息队列,消息将在这个队列传递,如不存在,则创建。durable=True 代表消息队列持久化存储,False 非持久化存储
result = channel.queue_declare(queue='python-test',durable=True)
# 声明exchange,由exchange指定消息在哪个队列传递,如不存在,则创建.durable = True 代表exchange持久化存储,False 非持久化存储
channel.exchange_declare(exchange='python-test', durable=True)
注意:如果已存在一个非持久化的 queue 或 exchange ,执行上述代码会报错,因为当前状态不能更改 queue 或 exchange 存储属性,需要删除重建。如果 queue 和 exchange 中一个声明了持久化,另一个没有声明持久化,则不允许绑定。
# 向队列插入数值 routing_key是队列名。delivery_mode = 2 声明消息在队列中持久化,delivery_mod = 1 消息非持久化
channel.basic_publish(exchange = '',routing_key = 'python-test',body = message,properties=pika.BasicProperties(delivery_mode=2))
# fanout_publisher.py
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare('logs', 'fanout')
#message = ' '.join(sys.argv[1:]) or "info: Hello World!"
message = "info: Hello World!"
# 广播模式下queue不用写。
channel.basic_publish(exchange='logs',
routing_key='',
body=message)
print(" [x] Sent %r" % message)
connection.close()
# _*_coding:utf-8_*_
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='fanout')
# 不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
result = channel.queue_declare('', exclusive=True)
# 上面随机生成的queue
queue_name = result.method.queue
# queue 绑定到logs转发器上, 通过自动生成的queue连接转发器
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_name, callback, True)
channel.start_consuming()
# direct_publisher
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
exchange_type='direct')
severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
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()
# direct_consumer
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
exchange_type='direct')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
# 获取输入的级别列表
severities = sys.argv[1:]
if not severities:
sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
sys.exit(1)
# 所有发到severity参数的消息都收,其他的consumer中没有这个参数
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(queue_name, callback, True)
channel.start_consuming()
匹配关键字发送.info,比如消息后缀名为.info。相对于direct写死更加灵活。
python topic_consumer.py *.info
python topic_consumer.py *.error mysql.*
python topic_publisher.py test.error
# topic_publisher
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()
# topic_consumer.py
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))
# rpc_client
import pika, time
import uuid
class FibonacciRpcClient(object):
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
self.channel = self.connection.channel()
# 自动创建一个queue
result = self.channel.queue_declare('', exclusive=True)
print(result.method.queue)
self.callback_queue = result.method.queue
# 只要收到服务器消息 就调用on_response函数
self.channel.basic_consume(self.callback_queue, self.on_response, True)
def on_response(self, ch, method, props, body):
# 确定服务器回消息的准确 哪个客户段给的id就返回哪个客户端
if self.corr_id == props.correlation_id:
self.response = body
def call(self, n):
self.response = None
self.corr_id = str(uuid.uuid4())
# 发的时候带着服务端需要回给的 队列名callback_queue 和 生产的唯一字符串corr_id
self.channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
reply_to=self.callback_queue,
correlation_id=self.corr_id,
),
body=str(n))
# 一直等待直到初始化的basic_consume被执行。就代表服务器回消息啦
while self.response is None:
# 可以理解为非阻塞版的start_consuming 过一段时间检测一下
self.connection.process_data_events()
# 这里可以继续发消息不用等待 前面uuid可以保证返回消息返回对应问题
print("检测一下,有消息吗?")
time.sleep(0.5)
return int(self.response)
fibonacci_rpc = FibonacciRpcClient()
print(" [x] Requesting fib(30)")
# 客户段发命令
response = fibonacci_rpc.call(30)
print(" [.] Got %r" % response)
# rpc_server
import pika
import time
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='rpc_queue')
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):
n = int(body)
print(" [.] fib(%s)" % n)
response = fib(n)
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id=props.correlation_id),
body=str(response))
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume('rpc_queue', on_request)
print(" [x] Awaiting RPC requests")
channel.start_consuming()