Golang学习实战笔记-基础 > golang实战之grpc微服务编程
protobuf protobuf扩展

一. 安装

需要两个文件protoc.exe 和 protoc-gen-go

1、下载protobuf的编译器protoc 具体方式可以参考上一篇文章


2、获取protobuf的编译器插件protoc-gen-go

    进入GOPATH目录 运行

1

go get -u github.com/golang/protobuf/protoc-gen-go

    如果成功,会在GOPATH/bin下生成protoc-gen-go.exe文件

二 . 测试

1.执行下面文件生成 grpc.pb.go文件

 生成client代码   protoc  -I=. --go_out=.  grpc.proto 

 生成server代码  protoc -I=def  --go_out=plugins=grpc:.    pos.server.proto

2. 运行测试代码

package main;
import (
"github.com/golang/protobuf/proto"
"github.com/gw123/GMQ/demo/grpc/inf"
"io/ioutil"
"os"
"fmt"
)
func write() {
p1 := &inf.Person{
Id:   1,
Name: "小张",
Phones: []*inf.Phone{
{Type: inf.PhoneType_HOME, Number: "111111111"},
{Type: inf.PhoneType_WORK, Number: "222222222"},
},
};
p2 := &inf.Person{
Id:   2,
Name: "小王",
Phones: []*inf.Phone{
{Type: inf.PhoneType_HOME, Number: "333333333"},
{Type: inf.PhoneType_WORK, Number: "444444444"},
},
};
//创建地址簿
book := &inf.ContactBook{};
book.Persons = append(book.Persons, p1);
book.Persons = append(book.Persons, p2);
//编码数据
data, _ := proto.Marshal(book);
//把数据写入文件
ioutil.WriteFile("./inf.txt", data, os.ModePerm);
}
func read() {
//读取文件数据
data, _ := ioutil.ReadFile("./inf.txt");
book := &inf.ContactBook{};
//解码数据
proto.Unmarshal(data, book);
for _, v := range book.Persons {
fmt.Println(v.Id, v.Name);
for _, vv := range v.Phones {
fmt.Println(vv.Type, vv.Number);
}
}
}
func main() {
write();
read();
}