安装步骤(默认root用户)
- 从github上下载:
git clone https://github.com/protocolbuffers/protobuf.git - 解决编译protobuf库文件工具:
autoconf automake libtool curl make g++ unzip;通过命令:yum -y install autoconf automake libtool curl make gcc-c++ unzip libffi-dev安装(如果没有yum就先安装yum,centos8.3中输入yum命令,如果未安装,会提示是否需要安装,输入y即可) - 输入命令:
cd protobuf进入protobuf文件夹下 - 输入命令:
./autogen.sh进行环境检查 - 输入命令:
../configure进行配置文件检查(最后会有警告,但问题不大,不用管) - 输入命令:
make编译该文件 - 输入命令:
make install将编译后的文件安装到指定目录中(/usr/local/include/google/protobuf) - 输入命令:
ldconfig刷新共享库(重要!) - 输入命令:
protoc -h,有命令选项输出即安装成功
go语言还需要安装扩展包
- 输入命令:
go get github.com/golang/protobuf下载go的protobuf扩展包(如果无法下载,需要通过命令go env -w GO111MODULE=on 和go env -w GOPROXY=https://goproxy.cn,direct打开模块和启用代理来进行下载)。下载的文件在目录/root/go/pkg/mod/github.com/golang中,其中/root/go为GOPATH(golang版本1.6)。 - 在目录
/root/go/pkg/mod/github.com/golang/protobuf@v1.5.2/protoc-gen-go中输入命令:go build,生成名为protoc-gen-go的可执行文件。 - 输入命令:
sudo mv protoc-gen-go /bin/将该可执行文件复制到linux的bin目录下,或者在go build后直接go install,这个可执行文件就会跑到GOPATH的bin目录下。到此即成功安装。
简单使用
- 创建一个go项目文件夹
gotext,该文件夹下包含prototext文件夹(用来创建和生成.proto和.pb.go文件),text文件夹(用来调用prototext下创建的.pb.go。) - 在文件夹
prototext下创建文件text.proto,在文件中输入测试文本:
syntax = "proto3"; // proto版本
option go_package = "./;prototext"; // //两个参数一个是生成地址,一个是包名
// 文本信息
message Test {
string name = 1;
repeated int32 w = 2;
int32 h = 3;
string motto = 4;
}
- 在
prototext目录下输入命令:protoc --go_out=./ *.proto,会在该目录下生成text.pb.go文件。 - 在文件夹
text下创建文件text.go文件:
package main
import (
"gotext/prototext"
"fmt"
)
func main() {
text := &prototext.Test {
Name: "panda",
W: []int32 {120, 125, 198, 180, 150, 195},
H: 180,
Motto: "这游戏真难!",
}
fmt.Println(text);
}
- 在
gotext目录下使用命令go mod init gotext和go mod tidy来模块化并安装依赖包。 - 在
text目录下执行go run text.go可以看到信息输出