1、环境搭建
# 安装官方的protoc工具
https://github.com/protocolbuffers/protobuf/releases
# 生成golang代码生成插件
go get -u github.com/golang/protobuf/protoc-gen-go
# 安装protoc引入的依赖
go get google.golang.org/protobuf/reflect/protoreflect
go get google.golang.org/protobuf/runtime/protoimpl
2、写代码
2.1、 定义协议文件
协议文件 gym.proto
syntax = "proto3";
// 1.14 后增加 go_package option
option go_package = "../gym";
//健身房
service Gym {
rpc BodyBuilding (Person) returns (Reply) {
}
}
//谁在健身
message Person {
string name = 1;
repeated string actions = 2;
}
//结果
message Reply {
int32 code = 1;
string msg = 2;
}
2.2、生成代码
在协议文件目录下
protoc --go_out=plugins=grpc:./ gym.proto
2.3、服务端代码
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"log"
"mygoing/gym"
"net"
)
type server struct {
gym.UnimplementedGymServer
}
func (s server) BodyBuilding(ctx context.Context, p *gym.Person) (*gym.Reply, error) {
fmt.Printf("%s正在健身, 动作: %s\n\n", p.Name, p.Actions)
return &gym.Reply{Code: 0, Msg: "ok"}, nil
}
func main() {
listen, err := net.Listen("tcp", ":8090")
if err != nil {
log.Fatalln(err)
}
s := grpc.NewServer()
gym.RegisterGymServer(s, &server{})
if err := s.Serve(listen); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
2.4、客户端代码
package main
import (
"context"
"google.golang.org/grpc"
"log"
"mygoing/gym"
"time"
)
const address = "localhost:8090"
func main() {
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalln("connection failed")
}
defer conn.Close()
client := gym.NewGymClient(conn)
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second)
defer cancelFunc()
r, err := client.BodyBuilding(ctx, &gym.Person{Name: "jack", Actions: []string{"xx", "yy"},
})
if err != nil {
log.Fatalf("error: %v", err)
}
log.Printf("code %d, msg: %s\n", r.Code, r.Msg)
}