安装go
//下载
wget https://dl.google.com/go/go1.13.4.linux-amd64.tar.gz
//解压
tar -zxvf go1.13.4.linux-amd64.tar.gz
//设置环境变量
export GOPATH=/root/go export PATH=$PATH:/root/go/bin
//检测是否成功
go version
安装go grpc
go get google.golang.org/grpc //使用 grpc SDK
https://github.com/protocolbuffers/protobuf/releases/ 找到合适的protoc编译器下载 并将bin目录下的protoc移动到/usr/bin/目录下
protoc --version //可以查看版本
go get -u github.com/golang/protobuf/protoc-gen-go //安装protoc go插件
protobuf文件定义
syntax = "proto3"; package proto; option go_package ="proto/proto"; message Members { repeated Member ss = 1; } message Member { string id = 1; string name = 2; } message Empty { } service User { rpc Users(Empty) returns (stream Members) {}; }
编译proto文件
protoc --go_out=plugins=grpc:. ./service.proto
server端代码
package grpc import ( "log" "awesomeProject/grpc/proto/proto"//编译protobuf文件生成的pb.go所在的包 "net" "google.golang.org/grpc" "math" ) type server struct {} func (s *server) Users(in *proto.Empty, out proto.User_UsersServer) error { var err error list := proto.Members{} for i := 0; i < 5; i++ { feature := proto.Member{ Id: "123", Name: "test", } list.Ss = append(list.Ss, &feature) } err = out.Send(&list) return err } func RunServer() error { sock, err := net.Listen("tcp", "127.0.0.1:9090") if err != nil { return err } var options = []grpc.ServerOption{ grpc.MaxRecvMsgSize(math.MaxInt32), grpc.MaxSendMsgSize(1073741824), } s := grpc.NewServer(options...) myServer := &server{} proto.RegisterUserServer(s, myServer) if err != nil { return err } if err := s.Serve(sock); err != nil { log.Fatalf("failed to serve: %v", err) } return nil }
client端代码
package grpc import ( "log" "awesomeProject/grpc/proto/proto"//编译protobuf文件生成pb.go所在的包 "google.golang.org/grpc" "fmt" "time" "context" ) func RunClient() error { conn, err := grpc.Dial("127.0.0.1:9090", grpc.WithInsecure()) // 如果要增加 Recv 可以接受的一个消息的数据量,必须增加 grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(100000000)) if err != nil { log.Fatalf("fail to dial: %v", err) return err } defer conn.Close() client := proto.NewUserClient(conn) ctx, cancel := context.WithTimeout(context.Background(), 10000*time.Second) defer cancel() stream, err := client.Users(ctx, &proto.Empty{}) for { data, err := stream.Recv() if err != nil { //fmt.Printf("error %v", err) return err } for i := 0;i < len(data.Ss);i++ { fmt.Println( data.Ss[i].GetId()) } } return err }
mac下编译linux可执行文件
GOOS=linux GOARCH=amd64 go build -o server main.go