内容简介:Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准。Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。在执行
什么是protobuf
Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准。
Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。
如何安装protobuf
-
在github获取protobuf源码,windows系统可以直接下载exe文件: https://github.com/google/protobuf/releases
-
macos和 linux 环境使用源码进行安装的步骤
# 获取源码包 wget https://github.com/google/protobuf/archive/v3.5.0.tar.gz # 解压缩并进入源码目录 tar -zxvf v3.5.0.tar.gz cd protobuf-3.5.0 # 生成configure文件 ./autogen.sh # 编译安装 ./configure make make check make install
在执行 ./autogen.sh
过程中可能会因缺乏automake依赖库而报错:
autoreconf: failed to run aclocal: No such file or directory
,要解决此错误,在linux系统可以通过 sudo yum install automake
或者 sudo apt-get install automake
安装automake,在macos系统可以通过 brew install automake
安装automake。
-
检测protobuf是否已成功安装
命令行执行
protoc --version。windows系统需要将protoc.exe文件所在的目录添加到环境变量。
如何使用protobuf
protobuf支持跨语言使用,很多主流的开发语言都有protobuf支持库,我们用golang来演示如何使用protobuf进行数据序列化。
- 在golang中安装protobuf相关的库
go get -u github.com/golang/protobuf/{protoc-gen-go,proto}
-
编写.proto文件
$GOPATH/src/test/protobuf/pb/user.proto
package pb;
message user {
int32 id = 1;
string name = 2;
}
message multi_user {
repeated user users = 1;
}
-
基于.proto文件生成数据操作代码
protoc --go_out=. user.proto
执行命令完成,在与
user.proto文件同级的目录下生成了一个user.pb.go文件 -
数据序列化演示
$GOPATH/src/test/protobuf/main.go
package main
import (
"log"
"test/protobuf/pb"
"github.com/golang/protobuf/proto"
)
func main() {
user1 := pb.User{
Id: *proto.Int32(1),
Name: *proto.String("Mike"),
}
user2 := pb.User{
Id: 2,
Name: "John",
}
users := pb.MultiUser{
Users: []*pb.User{&user1, &user2},
}
// 序列化数据
data, err := proto.Marshal(&users)
if err != nil {
log.Fatalln("Marshal data error: ", err)
}
println(users.Users[0].GetName()) // output: Mike
// 对已序列化的数据进行反序列化
var target pb.MultiUser
err = proto.Unmarshal(data, &target)
if err != nil {
log.Fatalln("Unmarshal data error: ", err)
}
println(target.GetUsers()[1].Name) // output: John
}
相关扩展
sublime插件:Protobuf Syntax Hightlighting
参考资料
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
共鸣:内容运营方法论
舒扬 / 机械工业出版社 / 2017-5-8 / 59.00
近5年来网络信息量增长了近10倍,信息极度过剩。移动互联网以碎片化、强黏度以及惊人的覆盖率给传统的商业环境带来了巨大的影响,向陈旧的广告、公关、媒体行业展开了深度的冲击。 传统的以渠道为中心的传播思想几近失效,优秀内容成为了各行业最稀缺的资产,这是时代赋予内容生产者的巨大机会。本书作者在多年经验和大量案例研究的基础上,总结出了移动互联网时代的内容运营方法论——共鸣,它将告诉我们如何收获核心粉......一起来看看 《共鸣:内容运营方法论》 这本书的介绍吧!