详解详解vue中使用中使用protobuf踩坑记踩坑记
主要介绍了vue中使用protobuf踩坑记,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习
价值,需要的朋友们下面随着小编来一起学习学习吧
官方解释为:
Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data – think XML, but smaller,
faster, and simpler. You define how you want your data to be structured once, then you can use special generated source
code to easily write and read your structured data to and from a variety of data streams and using a variety of languages.
You can even update your data structure without breaking deployed programs that are compiled against the "old" format.
翻译是(机翻---我英语不好)
协议缓冲区是用于序列化结构化数据的灵活,高效的自动化机制 - 思考XML,但更小,更快,更简单。您可以定义一次数据
的结构,然后您可以使用特殊的源代码轻松地将结构化数据写入各种数据流并使用各种语言读取和读取数据。您甚至可以更
新您的数据结构,而不会中断根据“旧”格式编译的已部署程序。
特点:
更简单
是3到10倍小
速度要快20到100倍
不太模糊
生成更易于以编程方式使用的数据访问类
代码代码
在github上写了个demo demo地址 有需要的可以下载下来跑一下就理解了。PS:如果觉得有用 请给我个小星星 (笔芯~)
使用使用
其实最开始我尝试使用一个第三方JSprotobuf.js protobuf.load 的时候浏览器报了个错illegal token '<' (/demo.proto, line 1) 查找了下官网
issue,大意应该是proto文件多了个字符,但是我查看过proto文件并没有发现有多的'<',怎么办呢,最后放弃使用第三方。用官方提供的
方法。
下载下载protobuf编译器编译器
下载地址 (我下载的是3.40版) github也提供了zip包,可自行下载 (目前最新版本是v3.6.0) 用来编译proto为JS文件方便调用
配置环境变量配置环境变量
由于公司用的是win10 只需要将下载的文件地址添加到path即可 Mac与window命令唯一的区别就是需要将protoc改成protoc.exe 前提是
需要添加环境变量
编写编写proto文件文件
为了确保前后一致,下面是后台写给我的一个测试proto,我司后台是java
syntax = "proto2";//protobuf版本
option java_package = "com.test.protobuf";
option java_outer_classname = "PersonMessage";
message Person {
required int32 id = 1;
optional string name = 2;
optional string email = 3;
repeated string list = 4;
extensions 100 to 1000;//允许扩展的ID
}
message PersonTree {
optional string id = 1;
optional string title = 2;
repeated PersonTree childs = 3;
}
extend Person {
optional int32 count = 101;
optional int32 likes_cnt= 102;
}
message PersonEx {
optional int32 id = 1;
extend Person {
optional int32 px = 103;
optional int32 py= 104;
}
optional Person p = 2;
}
评论0