官方解釋為:
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.
翻譯是(機翻---我英語不好)
協(xié)議緩沖區(qū)是用于序列化結(jié)構(gòu)化數(shù)據(jù)的靈活,高效的自動化機制 - 思考XML,但更小,更快,更簡單。您可以定義一次數(shù)據(jù)的結(jié)構(gòu),然后您可以使用特殊的源代碼輕松地將結(jié)構(gòu)化數(shù)據(jù)寫入各種數(shù)據(jù)流并使用各種語言讀取和讀取數(shù)據(jù)。您甚至可以更新您的數(shù)據(jù)結(jié)構(gòu),而不會中斷根據(jù)“舊”格式編譯的已部署程序。
特點:
更簡單 是3到10倍小 速度要快20到100倍 不太模糊 生成更易于以編程方式使用的數(shù)據(jù)訪問類代碼
在github上寫了個demo demo地址 有需要的可以下載下來跑一下就理解了。PS:如果覺得有用 請給我個小星星 (筆芯~)
使用
其實最開始我嘗試使用一個第三方JSprotobuf.js protobuf.load 的時候瀏覽器報了個錯illegal token '<' (/demo.proto, line 1) 查找了下官網(wǎng)issue,大意應(yīng)該是proto文件多了個字符,但是我查看過proto文件并沒有發(fā)現(xiàn)有多的'<',怎么辦呢,最后放棄使用第三方。用官方提供的方法。
下載protobuf編譯器
下載地址 (我下載的是3.40版) github也提供了zip包,可自行下載 (目前最新版本是v3.6.0) 用來編譯proto為JS文件方便調(diào)用
配置環(huán)境變量
由于公司用的是win10 只需要將下載的文件地址添加到path即可 Mac與window命令唯一的區(qū)別就是需要將protoc改成protoc.exe 前提是需要添加環(huán)境變量
編寫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構(gòu)建一個工程目錄
npm install -g vue-clivue init webpack my-projectcd my-projectnpm installnpm run dev
新聞熱點
疑難解答
圖片精選