RabbitMQ實現了進階訊息佇列協定的開源訊息代理軟體。
在我公司的應用是Server推送用戶消息, 客戶端接收即時處理。
由於有主備兩台服務器, 故寫法就非最簡單的模式。
import pika
import json
import os
import time
#服務器主備兩台, 端口通常為5672
node1 = pika.URLParameters('amqp://
ServerQueueName:ServerQueuePassword
@
ServerIP
:5672/%2F')
node2 = pika.URLParameters('amqp://
ServerQueueName:ServerQueuePassword
@
ServerIP
:5672/%2F')
all_endpoints = [node1, node2]
connection = pika.BlockingConnection(all_endpoints)
channel = connection.channel()
print (' [*] Waiting for messages. To exit press CTRL+C')
#處理接收訊息
def on_message(channel, method_frame, header_frame, body):
print(method_frame.delivery_tag)
print(body)
message = body.decode('utf8')
print(" [x] Received %s."% message)
if message!='':
input_obj = json.loads(message)
time.sleep(1)
#auto_ack =True 回應給服務器表接收
channel.basic_consume(queue= ServerQueueName ,on_message_callback=on_message, auto_ack=True )
try:
channel.start_consuming()
except KeyboardInterrupt:
channel.stop_consuming()
connection.close()
print (' [*] KeyboardInterrupt')
留言列表