1. 程式人生 > >python第五十九天-----補上筆記

python第五十九天-----補上筆記

函數 display closed b- lba import bind ever info

rabbitmq_server_topic topic模式

技術分享
 1 #!/usr/bin/env python
 2 #{data} {time}
 3 #_*_coding:utf-8_*_
 4 
 5 import pika,sys,time
 6 connection = pika.BlockingConnection(pika.ConnectionParameters(
 7                localhost))
 8 channel = connection.channel()#管道
 9 
10 
11 
12 #severity = sys.argv[1] if len(sys.argv) > 1 else ‘info‘#啟動參數 默認無參數為 info 級別
13 routing_key= sys.argv[1] if len(sys.argv) > 1 else anorrymous.info#啟動參數 默認無參數為 info 級別 14 msg=‘‘.join(sys.argv[2:]) or info:消息默認發送………#啟動參數 為空,發默認消息 15 for i in range(10): 16 time.sleep(1) 17 channel.basic_publish(exchange=direct_logs,#綁定頻道 18 #routing_key=severity,#默認的消息隊列級別
19 routing_key=routing_key,#默認的消息隊列級別 20 body=msg+str(i), 21 #properties=pika.BasicProperties(delivery_mode=2)#持久化 廣播不能使用 22 ) 23 #print(msg,severity) 24 print(msg,routing_key) 25 connection.close()
26 #channel.close()
View Code

topic_client: 可按級別來接收 廣播

技術分享
 1 #!/usr/bin/env python
 2 #{data} {time}
 3 #_*_coding:utf-8_*_
 4 
 5 import pika,time,sys
 6 
 7 connection = pika.BlockingConnection(pika.ConnectionParameters(
 8                localhost ))
 9 channel = connection.channel()
10 
11 channel.exchange_declare(exchange=direct_logs,#定義一個接收的頻道
12                          type=topic)
13 
14 reult=channel.queue_declare(exclusive=True)#隨機生成唯一的隊列名,會在消息接收後自動刪除
15 queuename=reult.method.queue#隊列名 自動生成
16 
17 
18 #severities = sys.argv[1:]
19 binding_key = sys.argv[1:]
20 #if not severities:
21 if not binding_key:
22     sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])#啟動接收的消息級別
23     sys.exit(1)
24 
25 #for severity in severities:#循環接收各級別的消息
26 for severity in binding_key:#循環接收各級別的消息
27     channel.queue_bind(exchange=direct_logs,
28                        queue=queuename,
29                        routing_key=severity)
30 
31 def callback(ch, method, properties, body):#回調函數
32     print(接收消息中…………)
33     #time.sleep(5)
34     print(" [x] Received %r" % body.decode())
35     ch.basic_ack(delivery_tag=method.delivery_tag)
36 
37 
38 channel.basic_qos(prefetch_count=1)#同時只處理一個消息
39 channel.basic_consume(callback,#接收到消息調用回調函數 callback
40                       queue=queuename,
41                       #no_ack=True
42                        )
43 
44 print( [*] 接收消息中. To exit press CTRL+C)
45 
46 channel.start_consuming()#啟動消息接收
View Code

python第五十九天-----補上筆記