1. 程式人生 > >python模擬上報訊息到rabbitMQ(protobuf)

python模擬上報訊息到rabbitMQ(protobuf)

 

 

1.下載安裝protobuf

  下載地址:https://github.com/protocolbuffers/protobuf/releases

  下載這兩個安裝包:protobuf-all-3.6.1.zip和protoc-3.6.1-win32.zip

 

  解壓之後安裝:進入python目錄

cmd進入該目錄安裝

安裝好之後檢視:protoc --version

 

2.編寫和轉換proto檔案

3.用protoc.exe編譯proto檔案

編寫的proto檔案存放處

編譯生成的py指令碼檔案

4.根據編寫的proto文字,編寫python指令碼傳送SlotMessage訊息到rabbitmq

# -*- coding: utf-8 -*-
#!/usr/bin/env python

import binascii
import pika
import datetime
from Simulate import slot_pb2


# rabbitmq 配置資訊
MQ_CONFIG = {
"host": "XXXXXXX",
"port": XXXXX,
"vhost": "/",
"user": "XXXXX",
"passwd": "XXXXX",
"exchange": "XXXXX",
}

#傳送的指令訊息
def message():
time1 = datetime.datetime.now() # 獲取當前時間
SlotMessage_auth = slot_pb2.SlotMessage()
SlotMessage_auth.openId ="XXXXXXX"
SlotMessage_auth.productId ="XXXXXX"
SlotMessage_auth.nodeEui = "XXXXXXX"
SlotMessage_auth.command = slot_pb2.SlotMessage.UPLINK
SlotMessage_auth.timestamp =str(time1)
SlotMessage_auth.appMessageType = XXX
Msg_Payload = SlotMessage_auth.payload
#傳送的指令
Msg_Payload.data = binascii.a2b_hex("XXXXXXXXX")
msg = SlotMessage_auth.SerializeToString()
return msg

#連線rabbitMQ推送訊息
def start_publish(message):
credentials = pika.PlainCredentials(MQ_CONFIG.get("user"), MQ_CONFIG.get("passwd"))
parameters = pika.ConnectionParameters(MQ_CONFIG.get("host"), MQ_CONFIG.get("port"), MQ_CONFIG.get("vhost"),credentials=credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
channel.basic_publish(exchange=MQ_CONFIG.get("exchange"), routing_key="", body=message)
print(" [x] Sent %r" % message)
connection.close()

if __name__ == '__main__':
msg= message()
start_publish(msg)


執行slot_test.py指令碼就相當於傳送了一條指令訊息到rabbitmq