python第五十九天-----补上笔记

时间:2022-02-28 04:28:56

rabbitmq_server_topic    topic模式

 #!/usr/bin/env python
#{data} {time}
#_*_coding:utf-8_*_ import pika,sys,time
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()#管道 #severity = sys.argv[1] if len(sys.argv) > 1 else 'info'#启动参数 默认无参数为 info 级别
routing_key= sys.argv[1] if len(sys.argv) > 1 else 'anorrymous.info'#启动参数 默认无参数为 info 级别
msg=''.join(sys.argv[2:]) or 'info:消息默认发送………'#启动参数 为空,发默认消息
for i in range(10):
time.sleep(1)
channel.basic_publish(exchange='direct_logs',#绑定频道
#routing_key=severity,#默认的消息队列级别
routing_key=routing_key,#默认的消息队列级别
body=msg+str(i),
#properties=pika.BasicProperties(delivery_mode=2)#持久化 广播不能使用
)
#print(msg,severity)
print(msg,routing_key)
connection.close()
#channel.close()

topic_client:  可按级别来接收  广播

 #!/usr/bin/env python
#{data} {time}
#_*_coding:utf-8_*_ import pika,time,sys connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost' ))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs',#定义一个接收的频道
type='topic') reult=channel.queue_declare(exclusive=True)#随机生成唯一的队列名,会在消息接收后自动删除
queuename=reult.method.queue#队列名 自动生成 #severities = sys.argv[1:]
binding_key = sys.argv[1:]
#if not severities:
if not binding_key:
sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])#启动接收的消息级别
sys.exit(1) #for severity in severities:#循环接收各级别的消息
for severity in binding_key:#循环接收各级别的消息
channel.queue_bind(exchange='direct_logs',
queue=queuename,
routing_key=severity) def callback(ch, method, properties, body):#回调函数
print('接收消息中…………')
#time.sleep(5)
print(" [x] Received %r" % body.decode())
ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1)#同时只处理一个消息
channel.basic_consume(callback,#接收到消息调用回调函数 callback
queue=queuename,
#no_ack=True
) print(' [*] 接收消息中. To exit press CTRL+C') channel.start_consuming()#启动消息接收