首页 > 语言 > JavaScript > 正文

详解vue中使用protobuf踩坑记

2024-05-06 15:39:46
字体:
来源:转载
供稿:网友

官方解释为:

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;}

使用vue-cli构建一个工程目录

npm install -g vue-clivue init webpack my-projectcd my-projectnpm installnpm run dev            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选