很久没使用grpc,命令及写法发生了变化:
mac 安装protoc: brew install protobuf
项目:go get google.golang.org/grpc
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
1、生成xx.pb.go, xx_grpc.pb.go文件的两种命令:
1、 protoc --go_out=paths=source_relative:. --go-grpc_out=paths=source_relative:. 路径/文件名.proto
2、 protoc -I=. --go_out=paths=source_relative:. --go-grpc_out=./ --go-grpc_opt=paths=source_relative 路径/文件名.proto
2、编写自定义的grpc server处理继承时,需要引入生成的xx_grpc.pb.go 的UniplementedXxxServer
proto文件内容:
syntax = "proto3"; package protocol; option go_package = "./proto"; message RpcGetUserInfoRequest { string user_id = 1; } message RpcGerUserInfoResponse { string name = 1; string created_time = 2; } service UserService { rpc GetUserInfo(RpcGetUserInfoRequest) returns (RpcGerUserInfoResponse) {} }
自定义实现的server服务端:
package protoserver import ( "context" "param/models" "param/proto" ) type RpcUserService struct { proto.UnimplementedUserServiceServer // 引入这个文件才算继承 } // 实现方法 func (sf RpcUserService) GetUserInfo(c context.Context, request *proto.RpcGetUserInfoRequest) (*proto.RpcGerUserInfoResponse, error) { uid := request.UserId var user = new(models.User) err := sf.DB("users").Where("user_id", uid).Take(&user) response := proto.RpcGerUserInfoResponse{ Name: user.Name, CreatedTime: user.CreatedTime, } return &response, err }
main.go 处理grpc部分: func rpcInit() { defer func() { if err := recover(); err != nil { fmt.Println("err rpc", err) } }() lis, err := net.Listen("tcp", ":8031") if err != nil { fmt.Printf("failed to listen: %v", err) return } rpcServer := grpc.NewServer() proto.RegisterUserServiceServer(rpcServer, &protoserver.RpcUserService{}) if err = rpcServer.Serve(lis); err != nil { fmt.Printf("failed to serve: %v", err) } }
grpc客户端部分:
package protoclient import ( "context" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "param/proto" "time" ) func GetRpcUserInfo() { var uid = "cbf0lqc32urbmefv47sg" conn, err := grpc.Dial(":8031", grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { fmt.Println("conn fail:", err) return } defer conn.Close() ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second) defer cancel() requestParams := &proto.RpcGetUserInfoRequest{ UserId: uid, } rpcClient := proto.NewUserServiceClient(conn) info, err := rpcClient.GetUserInfo(ctx, requestParams) if err != nil { fmt.Println("GetUserInfo fail:", err) return } fmt.Println(fmt.Sprintf("user.name:%s user.created_time:%s", info.Name, info.CreatedTime)) }
每天都是不想努力的一天....