前言
本学习总结皆为个人学习过程中的一些笔记以及理解,有错误之处请多多指正!
草稿区
安装grpc和代码
安装协议编辑器插件
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
更新path
export PATH="$PATH:$(go env GOPATH)/bin"
编译.proto文件
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative ./文件路径
.proto文件注意事项
编写 option go_package = “./;包名”
服务端
取出server
定义一个server结构体来实现包中的Unimplemented包名Server
挂载方法
实现proto中所声明的方法
注册服务
使用NewServer方法获取服务器,使用包中的Register包名Server来注册服务(第一个参数为服务器,第二个参数为server结构体)
创建监听
使用服务器的.serve方法进行监听,监听地址用net.Listen声明连接类型和地址
客户端
创建链接
conn, err := grpc.NewClient("localhost:7777", grpc.WithTransportCredentials(insecure.NewCredentials()))
创建客户
client := hello_grpc.NewHelloGRPCClient(conn)
调用方法
req, err := client.SayHi(context.Background(), &hello_grpc.Req{Message: "我需要一个浆果!"})
获取返回值
fmt.Println(req.GetMessage())