博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
protobuf自解释message
阅读量:7044 次
发布时间:2019-06-28

本文共 1885 字,大约阅读时间需要 6 分钟。

将proto的定义和序列化的数据组成一个对象,在解码时使用message内部存储的proto定义和数据就可以实现proto消息的自解释。

代码

在proto发布的包内自带了descriptor引入该类型组装成如下格式:

syntax = "proto2";import 'google/protobuf/descriptor.proto';message SelfDescribingMessage {  // proto的定义  required google.protobuf.FileDescriptorProto proto_file = 1;  // 具体的message类型,由于一个proto中可以包含多个message  required string type_name = 2;  // 具体序列化的数据  required bytes message_data = 3;}

然后可以随便定义一个proto类型

syntax = "proto2";message Person{    optional string name=1;    optional int32 age=2;}

下面进行自定义类型的序列化和反序列化:

//序列化        //创建对象        byte[] data=Type.Person.newBuilder().setName("Myname").setAge(18).build().toByteArray();        //获得proto定义        DescriptorProtos.FileDescriptorProto desc=Type.getDescriptor().toProto();                //组件自解释对象,typename是具体message的名字        Demo.SelfDescribingMessage message=Demo.SelfDescribingMessage.newBuilder().setProtoFile(desc)                .setTypeName("Person").setMessageData(ByteString.copyFrom(data)).build();        //进行序列化        FileOutputStream fos=new FileOutputStream("D://message");        message.writeTo(fos);        fos.close();        //反序列化        //读取文件        FileInputStream fis=new FileInputStream("D://message");        Demo.SelfDescribingMessage fileMessage=Demo.SelfDescribingMessage.parseFrom(fis);        //获得proto文件        DescriptorProtos.FileDescriptorProto fdp=fileMessage.getProtoFile();        Descriptors.FileDescriptor[] fds={};        //根据typename获得具体的message定义        Descriptors.Descriptor fileDesc=Descriptors.FileDescriptor.buildFrom(fdp,fds).findMessageTypeByName(fileMessage.getTypeName());        //读出消息并打印        System.out.println(DynamicMessage.parseFrom(fileDesc,fileMessage.getMessageData().toByteArray()));        fis.close();

下面就是程序的输出

name: "Myname"age: 18

总结

通过如上方法可以不用事先将proto的定义让客户端知道,而是将定义随着消息一起打包,对于需要极度灵活结构的需求可以使用。

转载于:https://www.cnblogs.com/resentment/p/6617803.html

你可能感兴趣的文章
为什么有了uwsgi还要nginx这个“前端”服务器
查看>>
Java BufferString
查看>>
Android笔记——Socket通信实现简单聊天室
查看>>
js修改onclick事件的四种方法
查看>>
我的友情链接
查看>>
linux文件管理必会知识
查看>>
Cocos2d-xna : 横版战略游戏开发实验4 Layer构建丰富的交互
查看>>
我的友情链接
查看>>
EDM邮件营销如何防止邮件被拒收和进垃圾箱
查看>>
Linux iostat监测IO状态
查看>>
No module named yum错误的解决办法
查看>>
机器学习之sklearn——EM
查看>>
VII Python(7)爬虫
查看>>
java位运算
查看>>
我的友情链接
查看>>
linux基本命令
查看>>
部署SCVMM 2012R2
查看>>
python编程题-句子的逆序
查看>>
我的友情链接
查看>>
表示数值的字符串
查看>>