前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Protobuf

Protobuf

原创
作者头像
vanguard
修改2021-01-04 10:57:40
1.2K0
修改2021-01-04 10:57:40
举报
文章被收录于专栏:vanguard

Protocol buffers are Google's language-neutral, platform-neutral, extensible 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.

谷歌出的一种语言无关、平台无关、可扩展的序列化结构数据的方法,它可用于(数据)通信协议、数据存储等。灵活,高效,自动化机制的结构数据序列化方法-可类比 XML,但是比 XML 更小(3 ~ 10倍)、更快(20 ~ 100倍)、更为简单。比JSON也小,最简单的理解就是健可以不用重复,通过定义数据的结构,然后使用特殊生成的源代码轻松的在各种数据流中使用各种语言进行编写和读取结构数据。甚至可以更新数据结构,而不破坏由旧数据结构编译的已部署程序。

  • Define message formats in a .proto file. / 定义数据格式
  • Use the protocol buffer compiler. / 编译文件成不同语言的实现
  • Use the Python protocol buffer API to write and read messages. / 调用所需要的库写和读

1. Define data format (t1d.proto):

代码语言:python
代码运行次数:0
复制
syntax = "proto3";

message Device {
	string name = 1;
}

2. Compile file:

https://developers.google.com/protocol-buffers/docs/downloads

https://github.com/protocolbuffers/protobuf

代码语言:shell
复制
# NETWORK issue -> proxy
pip install protobuf
brew install protobuf
protoc --version

# make (option in mac)
./autogen.sh && ./configure && make
brew install autoconf && brew install automake
make check
sudo make install
which protoc

# Compile now
# protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/t1d.proto
# protoc --proto_path=./ --python_out=./ my_example.proto
protoc -I=./ --python_out=./data/ t1d.proto

3. Runtime write and read:

代码语言:python
代码运行次数:0
复制
import t1d_pb2

my_device = t1d_pb2.Device(name='IHU!')

with open('my_device.pb', 'wb') as f:
    f.write(my_device.SerializeToString())

with open('my_device.pb', 'rb') as f:
    new_device = t1d_pb2.Device().FromString(f.read())

  • Javascript version
代码语言:javascript
复制
protoc --js_out=import_style=commonjs,binary:. XXX.proto
npm install -g require
npm install -g browserify
npm install google-protobuf
var address = require('./address_pb');
module.exports = {
    DataProto: address
}
browserify exports.js -o  address_main.js
  • Java version

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档