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
 

猜你喜欢

转载自www.cnblogs.com/drct/p/9964457.html