关于go:go入门grpc第六章protoc生成的grpcpbgo文件解读

8次阅读

共计 1446 个字符,预计需要花费 4 分钟才能阅读完成。

更不便的在微信公众号阅读文章能够关注公众号:海生的 go 花园

一、介绍

在第五章,咱们学习了.pb.go 文件
《go 入门 grpc》第五章:protoc 生成的.pb.go 文件解读
本章咱们学习下 protoc --go-grpc_out 命令生成的_grpc.pb.go 文件。
咱们以 hello.proto 文件为例,代码如下:

syntax = "proto3";
package hello;
import "google/protobuf/timestamp.proto";

option go_package = "github/hisheng/grpc-demo1/api";

service Say {rpc SayHello (HelloRequest) returns (HelloReply) {}}

message HelloRequest {string name = 1;}

message HelloReply {
  string message = 1;
  google.protobuf.Timestamp last_updated = 2;
}

应用 protoc --go-grpc_out 命令生成了 hello_grpc.pb.go 文件。

package api
......
type SayClient interface {SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)
}
......
type SayServer interface {SayHello(context.Context, *HelloRequest) (*HelloReply, error)
    mustEmbedUnimplementedSayServer()}
......

次要有三局部

  1. package
  2. Server 服务端接口,以及实现
  3. Client 客户端接口,以及实现

二、Server 服务端接口,以及实现

三、Client 客户端接口,以及实现

SayClient 是 SayService 的 客户端。
次要包含定义了一个 SayClient 接口,以及一个 sayClient 构造体。
sayClient 构造体实现了 SayClient 接口。
对外提供一个 NewSayClient()来生成初始化 SayClient 客户端。

NewSayClient(cc grpc.ClientConnInterface) SayClient

type SayClient interface {

SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)

}

type sayClient struct {

cc grpc.ClientConnInterface

}

func NewSayClient(cc grpc.ClientConnInterface) SayClient {

return &sayClient{cc}

}

func (c sayClient) SayHello(ctx context.Context, in HelloRequest, opts …grpc.CallOption) (*HelloReply, error) {

out := new(HelloReply)
err := c.cc.Invoke(ctx, "/hello.Say/SayHello", in, out, opts...)
if err != nil {return nil, err}
return out, nil

}

正文完
 0