这是本节的多页打印视图。 点击此处打印.

返回本页常规视图.

编程语言

Supported languages - 支持的编程语言

Each gRPC language / platform has links to the following pages and more:

每种 gRPC 语言/平台都有以下页面的链接和更多内容:

  • Quick start 快速入门
  • Tutorials 教程
  • API reference API 参考

Select a language to get started:

选择一种语言开始:

1 - go

Go

https://grpc.io/docs/languages/go/

快速入门

​ 几分钟内运行您的第一个 Go gRPC 应用程序!

基础教程

​ 了解 Go gRPC 的基础知识。


学习更多

参考

其他

开发者故事和演讲

1.1 - 快速入门

Quick start - 快速入门

https://grpc.io/docs/languages/go/quickstart/

​ 本指南将通过一个简单的工作示例帮助您入门使用 Go 中的 gRPC。

先决条件

  • Go,任意三个最新主要版本Go 发行版

    有关安装说明,请参阅 Go 的 入门指南

  • Protocol Buffers 编译器 protoc第 3 版

    有关安装说明,请参阅 Protocol Buffer 编译器安装

  • Go 插件用于协议编译器:

    1. 使用以下命令安装 Go 的协议编译器插件

      1
      2
      
      $ go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
      $ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
      
    2. 更新您的 PATH,以便 protoc 编译器可以找到这些插件:

      1
      
      $ export PATH="$PATH:$(go env GOPATH)/bin"
      

获取示例代码

​ 该示例代码是 grpc-go 仓库的一部分。

  1. 下载仓库的 zip 文件 并解压,或者克隆仓库:

    1
    
    $ git clone -b v1.55.0 --depth 1 https://github.com/grpc/grpc-go
    
  2. 切换到快速入门示例目录:

    1
    
    $ cd grpc-go/examples/helloworld
    

运行示例

​ 从 examples/helloworld 目录开始:

  1. 编译并执行服务端代码:

    1
    
    $ go run greeter_server/main.go
    
  2. 从另一个终端编译并执行客户端代码,并查看客户端输出:

    1
    2
    
    $ go run greeter_client/main.go
    Greeting: Hello world
    

​ 恭喜!您刚刚使用 gRPC 运行了一个客户端-服务端(client-server )应用程序。

更新 gRPC 服务

In this section you’ll update the application with an extra server method. The gRPC service is defined using protocol buffers. To learn more about how to define a service in a .proto file see Basics tutorial. For now, all you need to know is that both the server and the client stub have a SayHello() RPC method that takes a HelloRequest parameter from the client and returns a HelloReply from the server, and that the method is defined like this:

​ 在本节中,您将使用额外的服务端方法更新应用程序。gRPC 服务使用Protocol Buffers定义。要了解有关如何在 .proto 文件中定义服务的更多信息,请参阅基础教程。目前,您只需要知道服务端和客户端存根都有一个 SayHello() 的 RPC 方法,该方法从客户端接收一个 HelloRequest 参数,并从服务端返回一个 HelloReply,该方法定义如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// greeting 服务的定义。
service Greeter {
  // Sends a greeting 发送问候
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// 包含用户名称的请求消息。
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings 包含 greetings 的响应消息
message HelloReply {
  string message = 1;
}

​ 打开 helloworld/helloworld.proto 文件,并添加一个新的 SayHelloAgain() 方法,使用相同的请求和响应类型:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// greeting 服务的定义。
service Greeter {
  // Sends a greeting 发送问候
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // Sends another greeting 发送另一个问候
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}

// 包含用户名称的请求消息。
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings 包含 greetings 的响应消息。
message HelloReply {
  string message = 1;
}

​ 记得保存文件!

重新生成 gRPC 代码

​ 在使用新的服务方法之前,您需要重新编译已更新的 .proto 文件。

​ 仍然位于 examples/helloworld 目录中,运行以下命令:

1
2
3
$ protoc --go_out=. --go_opt=paths=source_relative \
    --go-grpc_out=. --go-grpc_opt=paths=source_relative \
    helloworld/helloworld.proto

​ 这将重新生成 helloworld/helloworld.pb.gohelloworld/helloworld_grpc.pb.go 文件,其中包含:

  • 用于填充、序列化和检索 HelloRequestHelloReply 消息类型的代码。
  • 生成的客户端和服务端代码。

更新并运行应用程序

​ 您已经重新生成了服务端和客户端代码,但仍需要在该示例应用程序的人工编写部分中实现和调用新的方法。

更新服务端

​ 打开 greeter_server/main.go,并添加以下函数(这里应该叫做方法吧):

1
2
3
func (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
        return &pb.HelloReply{Message: "Hello again " + in.GetName()}, nil
}

更新客户端

​ 打开 greeter_client/main.go,并在 main() 函数体的末尾添加以下代码:

1
2
3
4
5
r, err = c.SayHelloAgain(ctx, &pb.HelloRequest{Name: *name})
if err != nil {
        log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.GetMessage())

​ 记得保存您的更改。

运行!

​ 像之前一样运行客户端和服务端。从 examples/helloworld 目录执行以下命令:

  1. 运行该服务端:

    1
    
    $ go run greeter_server/main.go
    
  2. 在另一个终端中运行该客户端。这次,在命令行参数中添加一个名称。

    1
    
    $ go run greeter_client/main.go --name=Alice
    

    您将看到以下输出:

    1
    2
    
    Greeting: Hello Alice
    Greeting: Hello again Alice
    

下一步

1.2 - 基础教程

Basics tutorial - 基础教程

https://grpc.io/docs/languages/go/basics/

​ 这是关于在 Go 中使用 gRPC 的基础教程。

​ 本教程为Go程序员提供了使用gRPC的基础介绍。

​ 通过完成这个示例,您将学会如何:

  • .proto 文件中定义一个服务。
  • 使用协议缓冲区编译器生成服务端和客户端代码。
  • 使用 Go gRPC API 为您的服务编写一个简单的客户端和服务端。

​ 本教程假设您已经阅读了gRPC 简介并熟悉protocol buffers(协议缓冲区)。请注意,本教程中的示例使用的是协议缓冲区语言的proto3版本:您可以在proto3语言指南Go生成代码指南中了解更多信息。

为什么使用gRPC?

​ 我们的示例是一个简单的路由映射应用,它允许客户端获取有关其路由上的特定信息,进而创建这些路由摘要,并让服务端和其他客户端交换路由信息(如路由更新)。

​ 使用gRPC,我们可以在一个.proto文件中定义我们的服务,并在gRPC支持的任何语言中生成客户端和服务端,这些客户端和服务端可以在各种环境中运行,从大型数据中心的服务器到您自己的平板电脑,gRPC会为不同语言和环境之间的通信复杂性提供支持。我们还可以获得使用协议缓冲区的所有优势,包括高效的序列化、简单的IDL(Interactive Data Language 交互式数据语言)和易于更新的接口。

准备

​ 您应该已经安装了生成客户端和服务端接口代码所需的工具 —— 如果尚未安装,请参阅快速入门中的先决条件章节的安装说明。

获取示例代码

​ 该示例代码是grpc-go存储库的一部分。

  1. 下载该存储库的zip文件并解压,或者克隆存储库:

    1
    
    $ git clone -b v1.55.0 --depth 1 https://github.com/grpc/grpc-go
    
  2. 切换到该示例目录:

    1
    
    $ cd grpc-go/examples/route_guide
    

定义服务

​ 我们的第一步(正如您从gRPC 简介中了解到的)是使用protocol buffers定义gRPC的*服务(service)以及方法的请求(request)响应(response)*类型。有关完整的.proto文件,请参见routeguide/route_guide.proto

​ 要定义一个服务(service),请在您的.proto文件中指定一个命名的service

1
2
3
service RouteGuide {
   ...
}

​ 然后,在服务(service )定义内部定义一些rpc方法,指定其请求(request )和响应(response )类型。gRPC允许您定义四种类型的服务(service )方法,所有这些方法都可在该RouteGuide服务(service )中使用:

  • 简单的RPC(simple RPC),其中客户端使用存根(stub )发送请求到服务端并等待响应返回,就像普通的函数调用一样。

    1
    2
    
    // 获取给定位置的 feature 。
    rpc GetFeature(Point) returns (Feature) {}
    
  • 服务端流式RPC(server-side streaming RPC),其中的客户端向其服务端发送请求并获得一个流以读取一系列返回的消息。该客户端从返回的流中读取,直到没有更多的消息为止。如我们的示例所示,通过在*响应(response)*类型之前放置stream关键字来指定服务端流式方法(server-side streaming method)。

    1
    2
    3
    4
    5
    6
    7
    8
    
    // Obtains the Features available within the given Rectangle.  Results are
    // streamed rather than returned at once (e.g. in a response message with a
    // repeated field), as the rectangle may cover a large area and contain a
    // huge number of features.
    // 获取给定矩形范围内的可用 Features 。
    // 结果以流式方式传输,而不是一次性返回(例如在带有重复(repeated)字段的响应消息中),
    // 因为该矩形可能涵盖了一个大范围并包含大量 features 。
    rpc ListFeatures(Rectangle) returns (stream Feature) {}
    
  • 客户端流式RPC(client-side streaming RPC),其中的客户端写入一系列消息并将它们发送到其服务端,再次使用提供的流。该客户端完成写入消息后,等待其服务端读取所有消息并返回其响应。通过在*请求(request)*类型之前放置stream关键字来指定客户端流式方法(client-side streaming method)。

    1
    2
    3
    4
    5
    
    // Accepts a stream of Points on a route being traversed, returning a
    // RouteSummary when traversal is completed.
    // 在遍历 route 时,接受一系列 Points 的流,当遍历完成时返回一个RouteSummary。
    rpc RecordRoute(stream Point) returns 
    (RouteSummary) {}
    
  • 双向流式RPC(bidirectional streaming RPC),双方都使用读写流(read-write stream)发送一系列消息。这两个流操作是独立的,因此其客户端们(clients,这里怎么翻译比较合适)和服务端们(servers,这里怎么翻译比较合适)可以按照任意顺序读取和写入:例如,服务端可以在写入响应之前等待接收所有客户端消息,或者它可以交替读取消息然后写入消息,或者其他读取和写入的组合。每个流中消息的顺序保持不变。通过在*请求(request )响应(response)*之前放置stream关键字来指定这种类型的方法。

    1
    2
    3
    4
    
    // Accepts a stream of RouteNotes sent while a route is being traversed,
    // while receiving other RouteNotes (e.g. from other users).
    // 在遍历 route 时接收一系列发送的 RouteNote,同时接收其他 RouteNote(例如来自其他用户)。
    rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
    

​ 我们的.proto文件还包含用于服务方法(service methods)中使用的所有请求和响应类型的protocol buffer消息类型定义 —— 例如,这是Point消息类型的定义:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
// Points 用E7表示法表示为纬度-经度对(度乘以10**7并四舍五入到最接近的整数)。
// 纬度(latitudes)应在+/- 90度范围内,经度(longitude)应在+/- 180度范围内(包括边界)。
message Point {
  int32 latitude = 1;
  int32 longitude = 2;
}

生成客户端和服务端代码

​ 接下来,我们需要从.proto服务定义中生成gRPC客户端和服务端接口。我们使用带有特殊gRPC Go插件的protocol buffer编译器protoc来实现这一点。这类似于我们在快速入门中所做的。

​ 在examples/route_guide目录中运行以下命令:

1
2
3
$ protoc --go_out=. --go_opt=paths=source_relative \
    --go-grpc_out=. --go-grpc_opt=paths=source_relative \
    routeguide/route_guide.proto

​ 运行此命令将在routeguide目录中生成以下文件:

  • route_guide.pb.go,其中包含用于填充(populate)、序列化(serialize)和检索(retrieve )请求和响应消息类型的所有protocol buffer代码。
  • route_guide_grpc.pb.go,其中包含以下内容:
    • 一个接口类型(或存根(stub)),供客户端调用,其中定义了RouteGuide服务中的方法。
    • 一个接口类型,供服务端实现,其中同样定义了RouteGuide服务中的方法。

创建服务端

​ 首先让我们看看如何创建RouteGuide服务端。如果您只对创建gRPC客户端感兴趣,可以跳过本节,直接阅读创建客户端(当然您可能还是会觉得有趣!)。

​ 使我们的RouteGuide服务发挥作用有两个部分(parts)工作要做:

  • 实现从我们的服务定义生成的服务接口:它是执行我们的服务的实际"工作(work)"。
  • 运行gRPC服务端以侦听来自客户端的请求并将其分派给正确的服务实现。

​ 您可以在server/server.go中找到我们的示例RouteGuide服务端。让我们更详细地看看它是如何工作的。

实现RouteGuide

​ 正如您所看到的,我们的服务端有一个routeGuideServer结构类型,实现了生成的RouteGuideServer接口:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
type routeGuideServer struct {
        ...
}
...

func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
        ...
}
...

func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
        ...
}
...

func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
        ...
}
...

func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
        ...
}
...
简单RPC

​ 该routeGuideServer实现了我们所有的服务方法。让我们先看最简单的类型,GetFeature,它只是从客户端获取一个Point,并从其数据库中(以Feature的形式)返回对应的feature信息。

1
2
3
4
5
6
7
8
9
func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
  for _, feature := range s.savedFeatures {
    if proto.Equal(feature.Location, point) {
      return feature, nil
    }
  }
  // 未找到feature,返回一个未命名feature
  return &pb.Feature{Location: point}, nil
}

​ 该方法接收一个用于RPC的上下文对象和客户端的Point协议缓冲区请求。它返回一个带有响应信息的Feature协议缓冲区对象和一个error。在该方法中,我们使用适当的信息填充Feature,然后将其与nil错误一起return,告诉gRPC我们已经完成了对该RPC的处理,并且该Feature可以返回给客户端。

服务端流式 RPC

​ 现在让我们来看一个流式 RPC 的例子。ListFeatures 是一个服务端流式 RPC,因此我们需要向客户端发送多个 Feature

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
  for _, feature := range s.savedFeatures {
    if inRange(feature.Location, rect) {
      if err := stream.Send(feature); err != nil {
        return err
      }
    }
  }
  return nil
}

​ 如您所见,与在我们的方法参数中获得简单的请求和响应对象不同,这次我们获得了一个请求对象(客户端希望在其中找到FeatureRectangle)和一个特殊的RouteGuide_ListFeaturesServer对象来编写我们的响应。

​ 在这个方法中,我们填充了我们需要返回的许多Feature对象,并使用RouteGuide_ListFeaturesServerSend()方法将它们写入。最后,就像在我们简单的RPC中一样,我们返回一个nil错误,告诉gRPC我们已经完成了响应的编写。如果在此调用中发生任何错误,我们将返回一个非nil错误;gRPC层将把它(即非nil错误)转换为适当的RPC状态,以发送到网络上。

客户端流式 RPC

​ 现在让我们看一些稍微复杂一点的东西:客户端流式方法 RecordRoute,我们从客户端获取一系列的 Point,并返回一个包含有关他们行程信息的单个 RouteSummary。如您所见,这次该方法根本没有请求参数。相反,它获取了一个 RouteGuide_RecordRouteServer 流,服务端可以使用该流来读取和写入消息 —— 它可以使用其 Recv() 方法接收客户端消息,并使用其 SendAndClose() 方法返回单个响应。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
  var pointCount, featureCount, distance int32
  var lastPoint *pb.Point
  startTime := time.Now()
  for {
    point, err := stream.Recv()
    if err == io.EOF {
      endTime := time.Now()
      return stream.SendAndClose(&pb.RouteSummary{
        PointCount:   pointCount,
        FeatureCount: featureCount,
        Distance:     distance,
        ElapsedTime:  int32(endTime.Sub(startTime).Seconds()),
      })
    }
    if err != nil {
      return err
    }
    pointCount++
    for _, feature := range s.savedFeatures {
      if proto.Equal(feature.Location, point) {
        featureCount++
      }
    }
    if lastPoint != nil {
      distance += calcDistance(lastPoint, point)
    }
    lastPoint = point
  }
}

​ 在该方法体中,我们使用 RouteGuide_RecordRouteServerRecv() 方法重复地将客户端的请求读取到一个请求对象(在本例中为 Point),直到没有更多的消息为止:服务端需要在每次调用后检查从 Recv() 返回的错误。如果该错误是 nil,则流仍然有效,可以继续读取;如果是 io.EOF,则消息流已结束,服务端可以返回其 RouteSummary。如果它有任何其他值,我们将原样返回该错误,以便由 gRPC 层将其转换为 RPC 状态。

双向流式 RPC

​ 最后,让我们来看一下双向流式 RPC RouteChat()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
  for {
    in, err := stream.Recv()
    if err == io.EOF {
      return nil
    }
    if err != nil {
      return err
    }
    key := serialize(in.Location)
                ... // look for notes to be sent to client 查找要发送给客户端的注释
    for _, note := range s.routeNotes[key] {
      if err := stream.Send(note); err != nil {
        return err
      }
    }
  }
}

​ 这次我们获取一个 RouteGuide_RouteChatServer 流,就像在客户端流式示例中一样,它可以用于读取和写入消息。但是,这次我们通过方法的流返回值,而客户端仍然在向他们的消息流中写入消息。

​ 在这里,读取和写入的语法与我们的客户端流式方法非常相似,只是服务端使用流的 Send() 方法而不是 SendAndClose(),因为它需要写入多个响应。尽管每一方始终会按照写入的顺序接收到对方的消息,但客户端和服务端都可以按任何顺序读取和写入 —— 这些流操作完全独立。

启动服务端

​ 一旦我们实现了所有的方法,我们还需要启动一个 gRPC 服务端,以便客户端可以真正使用我们的服务。下面的代码片段展示了我们如何为我们的 RouteGuide 服务做到这一点:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))
if err != nil {
  log.Fatalf("failed to listen: %v", err)
}
var opts []grpc.ServerOption
...
grpcServer := grpc.NewServer(opts...)
pb.RegisterRouteGuideServer(grpcServer, newServer())
grpcServer.Serve(lis)

​ 要构建和启动服务端,我们需要:

  1. 通过 lis, err := net.Listen(...) 指定要用于侦听客户端请求的端口。
  2. 使用 grpc.NewServer(...) 创建一个 gRPC 服务端的实例。
  3. 将我们的服务实现注册到 gRPC 服务端(the gRPC server,怎么翻译?暂且翻译为gRPC服务端吧)中。
  4. 使用我们的端口详细信息调用服务端的 Serve() 方法,以进行阻塞等待,直到其进程被终止或调用了 Stop()

创建客户端

​ 在本节中,我们将介绍如何为我们的 RouteGuide 服务创建一个 Go 客户端。您可以在 grpc-go/examples/route_guide/client/client.go 中查看我们完整的示例客户端代码。

创建存根

​ 要调用服务方法,我们首先需要创建一个 gRPC 通道(channel),用于与服务端进行通信。我们通过将服务端地址和端口号传递给 grpc.Dial() 来创建通道,代码如下所示:

1
2
3
4
5
6
7
var opts []grpc.DialOption
...
conn, err := grpc.Dial(*serverAddr, opts...)
if err != nil {
  ...
}
defer conn.Close()

​ 当服务需要认证凭据(例如,TLS、GCE 凭据或 JWT 凭据)时,您可以使用 DialOptionsgrpc.Dial 中设置这些认证凭据。RouteGuide 服务不需要任何凭据。

​ 一旦设置了 gRPC 通道(channel),我们就需要一个客户端 存根(stub) 来执行 RPC 调用。我们可以使用从示例 .proto 文件生成的 pb 包提供的 NewRouteGuideClient 方法来获取它(即存根(stub))。

1
client := pb.NewRouteGuideClient(conn)

调用服务方法

​ 现在让我们来看一下如何调用我们的服务方法。请注意,在 gRPC-Go 中,RPC 在阻塞/同步模式下运行,这意味着 RPC 调用会等待服务端响应,并且要么返回响应,要么返回错误。

简单 RPC

​ 调用简单 RPC GetFeature 几乎与调用本地方法一样简单。

1
2
3
4
feature, err := client.GetFeature(context.Background(), &pb.Point{409146138, -746188906})
if err != nil {
  ...
}

​ 如您所见,我们在之前获取的存根上调用了该方法。在我们的方法参数中,我们创建并填充了一个请求协议缓冲区对象(在本例中是 Point)。我们还传递了一个 context.Context 对象,它允许我们在需要时更改 RPC 的行为,比如超时/取消正在进行的 RPC。如果该调用没有返回错误,那么我们可以从第一个返回值中读取来自服务端的响应信息。

1
log.Println(feature)
服务端流式 RPC

​ 接下来是调用服务端流式方法 ListFeatures,它返回一系列地理(geographical ) Feature 流。如果您已经阅读过创建服务端的内容,这其中一些内容可能会非常熟悉 —— 这两者都以类似的方式实现了流式RPC。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
rect := &pb.Rectangle{ ... }  // initialize a pb.Rectangle
stream, err := client.ListFeatures(context.Background(), rect)
if err != nil {
  ...
}
for {
    feature, err := stream.Recv()
    if err == io.EOF {
        break
    }
    if err != nil {
        log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
    }
    log.Println(feature)
}

​ 与简单的 RPC 类似,我们将上下文和请求传递给该方法。但是,我们不会收到一个响应对象,而是会收到一个RouteGuide_ListFeaturesClient的实例。客户端可以使用 RouteGuide_ListFeaturesClient 流来读取服务端的响应。

​ 我们使用RouteGuide_ListFeaturesClientRecv()方法重复读取服务端的响应到一个响应协议缓冲区对象(在本例中为Feature)中,直到没有更多的消息为止:客户端需要在每次调用后检查Recv()返回的错误err。如果是 nil,则流仍然有效,可以继续读取;如果是 io.EOF,则消息流已经结束;否则,必定存在一个RPC错误,该错误通过err传递。

客户端流式 RPC

​ 客户端流式方法 RecordRoute 与服务端方法类似,只是我们只传递上下文,并获得一个 RouteGuide_RecordRouteClient 流,我们用它来同时写入和读取消息。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Create a random number of random points 创建随机数量的随机点
r := rand.New(rand.NewSource(time.Now().UnixNano()))
pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points 至少遍历两个点
var points []*pb.Point
for i := 0; i < pointCount; i++ {
  points = append(points, randomPoint(r))
}
log.Printf("Traversing %d points.", len(points))
stream, err := client.RecordRoute(context.Background())
if err != nil {
  log.Fatalf("%v.RecordRoute(_) = _, %v", client, err)
}
for _, point := range points {
  if err := stream.Send(point); err != nil {
    log.Fatalf("%v.Send(%v) = %v", stream, point, err)
  }
}
reply, err := stream.CloseAndRecv()
if err != nil {
  log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
}
log.Printf("Route summary: %v", reply)

RouteGuide_RecordRouteClient 有一个 Send() 方法,我们可以使用它向服务端发送请求。当使用 Send() 将客户端的请求写入流中后,我们需要在流上调用 CloseAndRecv(),以告知 gRPC 我们已经完成写入并期望接收响应。我们从 CloseAndRecv() 返回的 err 中获取 RPC 的状态。如果状态是 nil,那么 CloseAndRecv() 的第一个返回值将是一个有效的服务端响应。

双向流式 RPC

​ 最后,让我们看一下双向流式 RPC RouteChat()。与 RecordRoute 类似,我们只传递上下文对象给该方法,并返回一个流,我们可以使用它来同时写入和读取消息。但是,这次我们通过方法的流返回值,而服务端仍然在向 它们的 消息流写入消息。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
stream, err := client.RouteChat(context.Background())
waitc := make(chan struct{})
go func() {
  for {
    in, err := stream.Recv()
    if err == io.EOF {
      // read done.
      close(waitc)
      return
    }
    if err != nil {
      log.Fatalf("Failed to receive a note : %v", err)
    }
    log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude)
  }
}()
for _, note := range notes {
  if err := stream.Send(note); err != nil {
    log.Fatalf("Failed to send a note: %v", err)
  }
}
stream.CloseSend()
<-waitc

​ 在这里,读取和写入的语法与我们的客户端流式方法非常相似,只是在调用完成后,我们使用流的 CloseSend() 方法。尽管每一方始终按照写入的顺序获取对方的消息,但客户端和服务端都可以按任意顺序读取和写入 —— 流操作完全独立。

试一试!

​ 在 examples/route_guide 目录执行以下命令:

  1. 运行服务端:

    1
    
    $ go run server/server.go
    
  2. 在另一个终端中运行客户端:

    1
    
    $ go run client/client.go
    

​ 你将看到类似以下的输出:

Getting feature for point (409146138, -746188906)
name:"Berkshire Valley Management Area Trail, Jefferson, NJ, USA" location:<latitude:409146138 longitude:-746188906 >
Getting feature for point (0, 0)
location:<>
Looking for features within lo:<latitude:400000000 longitude:-750000000 > hi:<latitude:420000000 longitude:-730000000 >
name:"Patriots Path, Mendham, NJ 07945, USA" location:<latitude:407838351 longitude:-746143763 >
...
name:"3 Hasta Way, Newton, NJ 07860, USA" location:<latitude:410248224 longitude:-747127767 >
Traversing 56 points.
Route summary: point_count:56 distance:497013163
Got message First message at point(0, 1)
Got message Second message at point(0, 2)
Got message Third message at point(0, 3)
Got message First message at point(0, 1)
Got message Fourth message at point(0, 1)
Got message Second message at point(0, 2)
Got message Fifth message at point(0, 2)
Got message Third message at point(0, 3)
Got message Sixth message at point(0, 3)

注意

​ 我们在本页面展示的客户端和服务端跟踪输出中省略了时间戳。

1.3 - ALTS

ALTS authentication ALTS身份验证

An overview of gRPC authentication in Go using Application Layer Transport Security (ALTS).

使用应用层传输安全(Application Layer Transport Security,ALTS)在Go中进行gRPC身份验证的概述。

Overview 概述

Application Layer Transport Security (ALTS) is a mutual authentication and transport encryption system developed by Google. It is used for securing RPC communications within Google’s infrastructure. ALTS is similar to mutual TLS but has been designed and optimized to meet the needs of Google’s production environments. For more information, take a look at the ALTS whitepaper.

应用层传输安全(ALTS)是由Google开发的相互认证和传输加密系统,用于保护Google基础架构内的RPC通信。ALTS类似于相互TLS,但经过设计和优化以满足Google生产环境的需求。有关更多信息,请参阅ALTS白皮书

ALTS in gRPC has the following features:

gRPC中的ALTS具有以下功能:

  • Create gRPC servers & clients with ALTS as the transport security protocol.
  • ALTS connections are end-to-end protected with privacy and integrity.
  • Applications can access peer information such as the peer service account.
  • Client authorization and server authorization support.
  • Minimal code changes to enable ALTS.
  • 使用ALTS作为传输安全协议创建gRPC服务器和客户端。
  • ALTS连接具有端到端的隐私和完整性保护。
  • 应用程序可以访问对等方信息,例如对等方服务帐号。
  • 支持客户端授权和服务器授权。
  • 最小的代码更改以启用ALTS。

gRPC users can configure their applications to use ALTS as a transport security protocol with few lines of code.

gRPC用户可以配置其应用程序以使用ALTS作为传输安全协议,只需几行代码。

Note that ALTS is fully functional if the application runs on Google Cloud Platform. ALTS could be run on any platforms with a pluggable ALTS handshaker service.

请注意,如果应用程序在Google Cloud Platform上运行,则ALTS是完全功能的。ALTS可以在任何平台上运行,只需具备可插拔的ALTS握手服务

gRPC Client with ALTS Transport Security Protocol 使用ALTS传输安全协议的gRPC客户端

gRPC clients can use ALTS credentials to connect to servers, as illustrated in the following code excerpt:

gRPC客户端可以使用ALTS凭据连接到服务器,如下面的代码摘录所示:

1
2
3
4
5
6
7
import (
  "google.golang.org/grpc"
  "google.golang.org/grpc/credentials/alts"
)

altsTC := alts.NewClientCreds(alts.DefaultClientOptions())
conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(altsTC))

gRPC Server with ALTS Transport Security Protocol 使用ALTS传输安全协议的gRPC服务器

gRPC servers can use ALTS credentials to allow clients to connect to them, as illustrated next:

gRPC服务器可以使用ALTS凭据允许客户端连接到它们,如下所示:

1
2
3
4
5
6
7
import (
  "google.golang.org/grpc"
  "google.golang.org/grpc/credentials/alts"
)

altsTC := alts.NewServerCreds(alts.DefaultServerOptions())
server := grpc.NewServer(grpc.Creds(altsTC))

Server Authorization 服务器授权

gRPC has built-in server authorization support using ALTS. A gRPC client using ALTS can set the expected server service accounts prior to establishing a connection. Then, at the end of the handshake, server authorization guarantees that the server identity matches one of the service accounts specified by the client. Otherwise, the connection fails.

gRPC使用ALTS具有内置的服务器授权支持。使用ALTS的gRPC客户端可以在建立连接之前设置预期的服务器服务帐号。然后,在握手结束时,服务器授权保证服务器标识与客户端指定的服务帐号之一匹配。否则,连接将失败。

1
2
3
4
5
6
7
8
9
import (
  "google.golang.org/grpc"
  "google.golang.org/grpc/credentials/alts"
)

clientOpts := alts.DefaultClientOptions()
clientOpts.TargetServiceAccounts = []string{expectedServerSA}
altsTC := alts.NewClientCreds(clientOpts)
conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(altsTC))

Client Authorization 客户端授权

On a successful connection, the peer information (e.g., client’s service account) is stored in the AltsContext. gRPC provides a utility library for client authorization check. Assuming that the server knows the expected client identity (e.g., foo@iam.gserviceaccount.com), it can run the following example codes to authorize the incoming RPC.

在成功建立连接后,对等方信息(例如,客户端的服务帐号)将存储在AltsContext中。gRPC提供了一个用于客户端授权检查的实用库。假设服务器知道预期的客户端身份(例如,foo@iam.gserviceaccount.com),它可以运行以下示例代码来对传入的RPC进行授权。

1
2
3
4
5
6
import (
  "google.golang.org/grpc"
  "google.golang.org/grpc/credentials/alts"
)

err := alts.ClientAuthorizationCheck(ctx, []string{"foo@iam.gserviceaccount.com"})

1.4 - API

API

文档

概述

​ grpc 包实现了一个名为 gRPC 的远程过程调用 (RPC) 系统。

​ 有关 gRPC 的更多信息,请访问 grpc.io

常量

View Source

const (
	SupportPackageIsVersion3 = true
	SupportPackageIsVersion4 = true
	SupportPackageIsVersion5 = true
	SupportPackageIsVersion6 = true
	SupportPackageIsVersion7 = true
)

The SupportPackageIsVersion variables are referenced from generated protocol buffer files to ensure compatibility with the gRPC version used. The latest support package version is 7.

SupportPackageIsVersion 变量在生成的协议缓冲区文件中被引用,以确保与使用的 gRPC 版本兼容。最新的支持包版本为 7。

Older versions are kept for compatibility.

旧版本保留以确保兼容性。

These constants should not be referenced from any other code.

这些常量不应从任何其他代码中引用。

View Source

const PickFirstBalancerName = "pick_first"

PickFirstBalancerName is the name of the pick_first balancer.

PickFirstBalancerName 是 pick_first 负载均衡器的名称。

View Source

const Version = "1.55.0"

Version is the current grpc version.

Version 是当前的 gRPC 版本。

变量

View Source

var DefaultBackoffConfig = BackoffConfig{
	MaxDelay: 120 * time.Second,
}

DefaultBackoffConfig uses values specified for backoff in https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.

DefaultBackoffConfig 使用在 https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md 中指定的退避值。

Deprecated: use ConnectParams instead. Will be supported throughout 1.x.

已弃用:请改用 ConnectParams。在 1.x 版本中将继续支持。

View Source

var EnableTracing bool

EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package. This should only be set before any RPCs are sent or received by this program.

EnableTracing 控制是否使用 golang.org/x/net/trace 包跟踪 RPC。这应该在该程序发送或接收任何 RPC 之前设置。

View Source

var (
	// ErrClientConnClosing indicates that the operation is illegal because
	// the ClientConn is closing.
	//
	// Deprecated: this error should not be relied upon by users; use the status
	// code of Canceled instead.
	// ErrClientConnClosing 表示操作非法,因为 ClientConn 正在关闭。
	//
	// 已弃用:用户不应依赖此错误;请使用 Canceled 状态代码。
	ErrClientConnClosing = status.Error(codes.Canceled, "grpc: the client connection is closing")
)

View Source

var ErrClientConnTimeout = errors.New("grpc: timed out when dialing")

ErrClientConnTimeout indicates that the ClientConn cannot establish the underlying connections within the specified timeout.

ErrClientConnTimeout 表示 ClientConn 无法在指定的超时时间内建立底层连接。

Deprecated: This error is never returned by grpc and should not be referenced by users.

已弃用:该错误从未被 grpc 返回过,用户不应引用此错误。

View Source

var ErrServerStopped = errors.New("grpc: the server has been stopped")

ErrServerStopped indicates that the operation is now illegal because of the server being stopped.

xxxxxxxxxx6 1import (2  “google.golang.org/grpc"3  “google.golang.org/grpc/credentials/alts"4)5​6err := alts.ClientAuthorizationCheck(ctx, []string{“foo@iam.gserviceaccount.com”})go

函数

func ClientSupportedCompressors <- v1.54.0

func ClientSupportedCompressors(ctx context.Context) ([]string, error)

ClientSupportedCompressors returns compressor names advertised by the client via grpc-accept-encoding header.

ClientSupportedCompressors 返回客户端通过 grpc-accept-encoding 头字段广告的压缩器名称。

The context provided must be the context passed to the server’s handler.

提供的上下文必须是传递给服务器处理程序的上下文。

Experimental 实验性的

Notice: This function is EXPERIMENTAL and may be changed or removed in a later release.

注意:此函数是实验性的,可能会在以后的版本中更改或移除。

funcCode DEPRECATED

func ErrorDesc DEPRECATED

func Errorf DEPRECATED

func Invoke

func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error

Invoke sends the RPC request on the wire and returns after response is received. This is typically called by generated code.

Invoke 将 RPC 请求发送到网络并在接收到响应后返回。通常由生成的代码调用。

DEPRECATED: Use ClientConn.Invoke instead.

已弃用:请改用 ClientConn.Invoke。

func Method <- v1.11.2

func Method(ctx context.Context) (string, bool)

Method returns the method string for the server context. The returned string is in the format of “/service/method”.

Method 返回服务器上下文的方法字符串。返回的字符串的格式为 “/service/method”。

func MethodFromServerStream <- v1.8.0

func MethodFromServerStream(stream ServerStream) (string, bool)

MethodFromServerStream returns the method string for the input stream. The returned string is in the format of “/service/method”.

MethodFromServerStream 返回输入流的方法字符串。返回的字符串的格式为 “/service/method”。

func NewContextWithServerTransportStream <- v1.11.0

func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context

NewContextWithServerTransportStream creates a new context from ctx and attaches stream to it.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func SendHeader

func SendHeader(ctx context.Context, md metadata.MD) error

SendHeader sends header metadata. It may be called at most once, and may not be called after any event that causes headers to be sent (see SetHeader for a complete list). The provided md and headers set by SetHeader() will be sent.

The error returned is compatible with the status package. However, the status code will often not match the RPC status as seen by the client application, and therefore, should not be relied upon for this purpose.

func SetHeader <- v1.0.3

func SetHeader(ctx context.Context, md metadata.MD) error

SetHeader sets the header metadata to be sent from the server to the client. The context provided must be the context passed to the server’s handler.

Streaming RPCs should prefer the SetHeader method of the ServerStream.

When called multiple times, all the provided metadata will be merged. All the metadata will be sent out when one of the following happens:

  • grpc.SendHeader is called, or for streaming handlers, stream.SendHeader.
  • The first response message is sent. For unary handlers, this occurs when the handler returns; for streaming handlers, this can happen when stream’s SendMsg method is called.
  • An RPC status is sent out (error or success). This occurs when the handler returns.

SetHeader will fail if called after any of the events above.

The error returned is compatible with the status package. However, the status code will often not match the RPC status as seen by the client application, and therefore, should not be relied upon for this purpose.

func SetSendCompressor <- v1.54.0

func SetSendCompressor(ctx context.Context, name string) error

SetSendCompressor sets a compressor for outbound messages from the server. It must not be called after any event that causes headers to be sent (see ServerStream.SetHeader for the complete list). Provided compressor is used when below conditions are met:

  • compressor is registered via encoding.RegisterCompressor
  • compressor name must exist in the client advertised compressor names sent in grpc-accept-encoding header. Use ClientSupportedCompressors to get client supported compressor names.

The context provided must be the context passed to the server’s handler. It must be noted that compressor name encoding.Identity disables the outbound compression. By default, server messages will be sent using the same compressor with which request messages were sent.

It is not safe to call SetSendCompressor concurrently with SendHeader and SendMsg.

Experimental

Notice: This function is EXPERIMENTAL and may be changed or removed in a later release.

func SetTrailer

func SetTrailer(ctx context.Context, md metadata.MD) error

SetTrailer sets the trailer metadata that will be sent when an RPC returns. When called more than once, all the provided metadata will be merged.

The error returned is compatible with the status package. However, the status code will often not match the RPC status as seen by the client application, and therefore, should not be relied upon for this purpose.

类型

type BackoffConfig DEPRECATED

type CallOption

type CallOption interface {
	// contains filtered or unexported methods
}

CallOption configures a Call before it starts or extracts information from a Call after it completes.

func CallContentSubtype <- v1.10.0

func CallContentSubtype(contentSubtype string) CallOption

CallContentSubtype returns a CallOption that will set the content-subtype for a call. For example, if content-subtype is “json”, the Content-Type over the wire will be “application/grpc+json”. The content-subtype is converted to lowercase before being included in Content-Type. See Content-Type on https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for more details.

If ForceCodec is not also used, the content-subtype will be used to look up the Codec to use in the registry controlled by RegisterCodec. See the documentation on RegisterCodec for details on registration. The lookup of content-subtype is case-insensitive. If no such Codec is found, the call will result in an error with code codes.Internal.

If ForceCodec is also used, that Codec will be used for all request and response messages, with the content-subtype set to the given contentSubtype here for requests.

func CallCustomCodec DEPRECATED

func FailFast DEPRECATED

func ForceCodec <- v1.19.0

func ForceCodec(codec encoding.Codec) CallOption

ForceCodec returns a CallOption that will set codec to be used for all request and response messages for a call. The result of calling Name() will be used as the content-subtype after converting to lowercase, unless CallContentSubtype is also used.

See Content-Type on https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for more details. Also see the documentation on RegisterCodec and CallContentSubtype for more details on the interaction between Codec and content-subtype.

This function is provided for advanced users; prefer to use only CallContentSubtype to select a registered codec instead.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func Header

func Header(md *metadata.MD) CallOption

Header returns a CallOptions that retrieves the header metadata for a unary RPC.

func MaxCallRecvMsgSize <- v1.4.0

func MaxCallRecvMsgSize(bytes int) CallOption

MaxCallRecvMsgSize returns a CallOption which sets the maximum message size in bytes the client can receive. If this is not set, gRPC uses the default 4MB.

func MaxCallSendMsgSize <- v1.4.0

func MaxCallSendMsgSize(bytes int) CallOption

MaxCallSendMsgSize returns a CallOption which sets the maximum message size in bytes the client can send. If this is not set, gRPC uses the default math.MaxInt32.

func MaxRetryRPCBufferSize <- v1.14.0

func MaxRetryRPCBufferSize(bytes int) CallOption

MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory used for buffering this RPC’s requests for retry purposes.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func OnFinish <- v1.54.0

func OnFinish(onFinish func(err error)) CallOption

OnFinish returns a CallOption that configures a callback to be called when the call completes. The error passed to the callback is the status of the RPC, and may be nil. The onFinish callback provided will only be called once by gRPC. This is mainly used to be used by streaming interceptors, to be notified when the RPC completes along with information about the status of the RPC.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func Peer <- v1.2.0

func Peer(p *peer.Peer) CallOption

Peer returns a CallOption that retrieves peer information for a unary RPC. The peer field will be populated after the RPC completes.

func PerRPCCredentials <- v1.4.0

func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption

PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials for a call.

func Trailer

func Trailer(md *metadata.MD) CallOption

Trailer returns a CallOptions that retrieves the trailer metadata for a unary RPC.

func UseCompressor <- v1.8.0

func UseCompressor(name string) CallOption

UseCompressor returns a CallOption which sets the compressor used when sending the request. If WithCompressor is also set, UseCompressor has higher priority.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func WaitForReady <- v1.18.0

func WaitForReady(waitForReady bool) CallOption

WaitForReady configures the action to take when an RPC is attempted on broken connections or unreachable servers. If waitForReady is false and the connection is in the TRANSIENT_FAILURE state, the RPC will fail immediately. Otherwise, the RPC client will block the call until a connection is available (or the call is canceled or times out) and will retry the call if it fails due to a transient error. gRPC will not retry if data was written to the wire unless the server indicates it did not process the data. Please refer to https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.

By default, RPCs don’t “wait for ready”.

type ClientConn

type ClientConn struct {
	// contains filtered or unexported fields
}

ClientConn represents a virtual connection to a conceptual endpoint, to perform RPCs.

A ClientConn is free to have zero or more actual connections to the endpoint based on configuration, load, etc. It is also free to determine which actual endpoints to use and may change it every RPC, permitting client-side load balancing.

A ClientConn encapsulates a range of functionality including name resolution, TCP connection establishment (with retries and backoff) and TLS handshakes. It also handles errors on established connections by re-resolving the name and reconnecting.

func Dial

func Dial(target string, opts ...DialOption) (*ClientConn, error)

Dial creates a client connection to the given target.

func DialContext <- v1.0.2

func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error)

DialContext creates a client connection to the given target. By default, it’s a non-blocking dial (the function won’t wait for connections to be established, and connecting happens in the background). To make it a blocking dial, use WithBlock() dial option.

In the non-blocking case, the ctx does not act against the connection. It only controls the setup steps.

In the blocking case, ctx can be used to cancel or expire the pending connection. Once this function returns, the cancellation and expiration of ctx will be noop. Users should call ClientConn.Close to terminate all the pending operations after this function returns.

The target name syntax is defined in https://github.com/grpc/grpc/blob/master/doc/naming.md. e.g. to use dns resolver, a “dns:///” prefix should be applied to the target.

func (*ClientConn) Close

func (cc *ClientConn) Close() error

Close tears down the ClientConn and all underlying connections.

func (*ClientConn) Connect <- v1.41.0

func (cc *ClientConn) Connect()

Connect causes all subchannels in the ClientConn to attempt to connect if the channel is idle. Does not wait for the connection attempts to begin before returning.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func (*ClientConn) GetMethodConfig <- v1.4.0

func (cc *ClientConn) GetMethodConfig(method string) MethodConfig

GetMethodConfig gets the method config of the input method. If there’s an exact match for input method (i.e. /service/method), we return the corresponding MethodConfig. If there isn’t an exact match for the input method, we look for the service’s default config under the service (i.e /service/) and then for the default for all services (empty string).

If there is a default MethodConfig for the service, we return it. Otherwise, we return an empty MethodConfig.

func (*ClientConn) GetState <- v1.5.2

func (cc *ClientConn) GetState() connectivity.State

GetState returns the connectivity.State of ClientConn.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func (*ClientConn) Invoke <- v1.8.0

func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error

Invoke sends the RPC request on the wire and returns after response is received. This is typically called by generated code.

All errors returned by Invoke are compatible with the status package.

func (*ClientConn) NewStream <- v1.8.0

func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)

NewStream creates a new Stream for the client side. This is typically called by generated code. ctx is used for the lifetime of the stream.

To ensure resources are not leaked due to the stream returned, one of the following actions must be performed:

  1. Call Close on the ClientConn.
  2. Cancel the context provided.
  3. Call RecvMsg until a non-nil error is returned. A protobuf-generated client-streaming RPC, for instance, might use the helper function CloseAndRecv (note that CloseSend does not Recv, therefore is not guaranteed to release all resources).
  4. Receive a non-nil, non-io.EOF error from Header or SendMsg.

If none of the above happen, a goroutine and a context will be leaked, and grpc will not call the optionally-configured stats handler with a stats.End message.

func (*ClientConn) ResetConnectBackoff <- v1.15.0

func (cc *ClientConn) ResetConnectBackoff()

ResetConnectBackoff wakes up all subchannels in transient failure and causes them to attempt another connection immediately. It also resets the backoff times used for subsequent attempts regardless of the current state.

In general, this function should not be used. Typical service or network outages result in a reasonable client reconnection strategy by default. However, if a previously unavailable network becomes available, this may be used to trigger an immediate reconnect.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func (*ClientConn) Target <- v1.14.0

func (cc *ClientConn) Target() string

Target returns the target string of the ClientConn.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func (*ClientConn) WaitForStateChange <- v1.5.2

func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool

WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or ctx expires. A true value is returned in former case and false in latter.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

type ClientConnInterface <- v1.27.0

type ClientConnInterface interface {
	// Invoke performs a unary RPC and returns after the response is received
	// into reply.
	Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...CallOption) error
	// NewStream begins a streaming RPC.
	NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
}

ClientConnInterface defines the functions clients need to perform unary and streaming RPCs. It is implemented by *ClientConn, and is only intended to be referenced by generated code.

type ClientStream

type ClientStream interface {
	// Header returns the header metadata received from the server if there
	// is any. It blocks if the metadata is not ready to read.
	Header() (metadata.MD, error)
	// Trailer returns the trailer metadata from the server, if there is any.
	// It must only be called after stream.CloseAndRecv has returned, or
	// stream.Recv has returned a non-nil error (including io.EOF).
	Trailer() metadata.MD
	// CloseSend closes the send direction of the stream. It closes the stream
	// when non-nil error is met. It is also not safe to call CloseSend
	// concurrently with SendMsg.
	CloseSend() error
	// Context returns the context for this stream.
	//
	// It should not be called until after Header or RecvMsg has returned. Once
	// called, subsequent client-side retries are disabled.
	Context() context.Context
	// SendMsg is generally called by generated code. On error, SendMsg aborts
	// the stream. If the error was generated by the client, the status is
	// returned directly; otherwise, io.EOF is returned and the status of
	// the stream may be discovered using RecvMsg.
	//
	// SendMsg blocks until:
	//   - There is sufficient flow control to schedule m with the transport, or
	//   - The stream is done, or
	//   - The stream breaks.
	//
	// SendMsg does not wait until the message is received by the server. An
	// untimely stream closure may result in lost messages. To ensure delivery,
	// users should ensure the RPC completed successfully using RecvMsg.
	//
	// It is safe to have a goroutine calling SendMsg and another goroutine
	// calling RecvMsg on the same stream at the same time, but it is not safe
	// to call SendMsg on the same stream in different goroutines. It is also
	// not safe to call CloseSend concurrently with SendMsg.
	SendMsg(m interface{}) error
	// RecvMsg blocks until it receives a message into m or the stream is
	// done. It returns io.EOF when the stream completes successfully. On
	// any other error, the stream is aborted and the error contains the RPC
	// status.
	//
	// It is safe to have a goroutine calling SendMsg and another goroutine
	// calling RecvMsg on the same stream at the same time, but it is not
	// safe to call RecvMsg on the same stream in different goroutines.
	RecvMsg(m interface{}) error
}

ClientStream defines the client-side behavior of a streaming RPC.

All errors returned from ClientStream methods are compatible with the status package.

func NewClientStream

func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)

NewClientStream is a wrapper for ClientConn.NewStream.

type Codec DEPRECATED

type Compressor DEPRECATED

type CompressorCallOption <- v1.11.0

type CompressorCallOption struct {
	CompressorType string
}

CompressorCallOption is a CallOption that indicates the compressor to use.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type ConnectParams <- v1.25.0

type ConnectParams struct {
	// Backoff specifies the configuration options for connection backoff.
	Backoff backoff.Config
	// MinConnectTimeout is the minimum amount of time we are willing to give a
	// connection to complete.
	MinConnectTimeout time.Duration
}

ConnectParams defines the parameters for connecting and retrying. Users are encouraged to use this instead of the BackoffConfig type defined above. See here for more details: https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type ContentSubtypeCallOption <- v1.11.0

type ContentSubtypeCallOption struct {
	ContentSubtype string
}

ContentSubtypeCallOption is a CallOption that indicates the content-subtype used for marshaling messages.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type CustomCodecCallOption <- v1.11.0

type CustomCodecCallOption struct {
	Codec Codec
}

CustomCodecCallOption is a CallOption that indicates the codec used for marshaling messages.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type Decompressor DEPRECATED

type DialOption

type DialOption interface {
	// contains filtered or unexported methods
}

DialOption configures how we set up the connection.

func FailOnNonTempDialError <- v1.0.5

func FailOnNonTempDialError(f bool) DialOption

FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on non-temporary dial errors. If f is true, and dialer returns a non-temporary error, gRPC will fail the connection to the network address and won’t try to reconnect. The default value of FailOnNonTempDialError is false.

FailOnNonTempDialError only affects the initial dial, and does not do anything useful unless you are also using WithBlock().

Use of this feature is not recommended. For more information, please see: https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func WithAuthority <- v1.2.0

func WithAuthority(a string) DialOption

WithAuthority returns a DialOption that specifies the value to be used as the :authority pseudo-header and as the server name in authentication handshake.

func WithBackoffConfig DEPRECATED

func WithBackoffMaxDelay DEPRECATED

func WithBlock

func WithBlock() DialOption

WithBlock returns a DialOption which makes callers of Dial block until the underlying connection is up. Without this, Dial returns immediately and connecting the server happens in background.

Use of this feature is not recommended. For more information, please see: https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md

func WithChainStreamInterceptor <- v1.21.0

func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption

WithChainStreamInterceptor returns a DialOption that specifies the chained interceptor for streaming RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All interceptors added by this method will be chained, and the interceptor defined by WithStreamInterceptor will always be prepended to the chain.

func WithChainUnaryInterceptor <- v1.21.0

func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption

WithChainUnaryInterceptor returns a DialOption that specifies the chained interceptor for unary RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All interceptors added by this method will be chained, and the interceptor defined by WithUnaryInterceptor will always be prepended to the chain.

func WithChannelzParentID <- v1.12.0

func WithChannelzParentID(id *channelz.Identifier) DialOption

WithChannelzParentID returns a DialOption that specifies the channelz ID of current ClientConn’s parent. This function is used in nested channel creation (e.g. grpclb dial).

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func WithCodec DEPRECATED

func WithCompressor DEPRECATED

func WithConnectParams <- v1.25.0

func WithConnectParams(p ConnectParams) DialOption

WithConnectParams configures the ClientConn to use the provided ConnectParams for creating and maintaining connections to servers.

The backoff configuration specified as part of the ConnectParams overrides all defaults specified in https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Consider using the backoff.DefaultConfig as a base, in cases where you want to override only a subset of the backoff configuration.

func WithContextDialer <- v1.19.0

func WithContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption

WithContextDialer returns a DialOption that sets a dialer to create connections. If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error’s Temporary() method to decide if it should try to reconnect to the network address.

func WithCredentialsBundle <- v1.16.0

func WithCredentialsBundle(b credentials.Bundle) DialOption

WithCredentialsBundle returns a DialOption to set a credentials bundle for the ClientConn.WithCreds. This should not be used together with WithTransportCredentials.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func WithDecompressor DEPRECATED

func WithDefaultCallOptions <- v1.4.0

func WithDefaultCallOptions(cos ...CallOption) DialOption

WithDefaultCallOptions returns a DialOption which sets the default CallOptions for calls over the connection.

func WithDefaultServiceConfig <- v1.20.0

func WithDefaultServiceConfig(s string) DialOption

WithDefaultServiceConfig returns a DialOption that configures the default service config, which will be used in cases where:

  1. WithDisableServiceConfig is also used, or
  2. The name resolver does not provide a service config or provides an invalid service config.

The parameter s is the JSON representation of the default service config. For more information about service configs, see: https://github.com/grpc/grpc/blob/master/doc/service_config.md For a simple example of usage, see: examples/features/load_balancing/client/main.go

func WithDialer DEPRECATED

func WithDisableHealthCheck <- v1.17.0

func WithDisableHealthCheck() DialOption

WithDisableHealthCheck disables the LB channel health checking for all SubConns of this ClientConn.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func WithDisableRetry <- v1.14.0

func WithDisableRetry() DialOption

WithDisableRetry returns a DialOption that disables retries, even if the service config enables them. This does not impact transparent retries, which will happen automatically if no data is written to the wire or if the RPC is unprocessed by the remote server.

func WithDisableServiceConfig <- v1.12.0

func WithDisableServiceConfig() DialOption

WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any service config provided by the resolver and provides a hint to the resolver to not fetch service configs.

Note that this dial option only disables service config from resolver. If default service config is provided, gRPC will use the default service config.

func WithInitialConnWindowSize <- v1.4.0

func WithInitialConnWindowSize(s int32) DialOption

WithInitialConnWindowSize returns a DialOption which sets the value for initial window size on a connection. The lower bound for window size is 64K and any value smaller than that will be ignored.

func WithInitialWindowSize <- v1.4.0

func WithInitialWindowSize(s int32) DialOption

WithInitialWindowSize returns a DialOption which sets the value for initial window size on a stream. The lower bound for window size is 64K and any value smaller than that will be ignored.

func WithInsecure DEPRECATED

func WithKeepaliveParams <- v1.2.0

func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption

WithKeepaliveParams returns a DialOption that specifies keepalive parameters for the client transport.

func WithMaxHeaderListSize <- v1.14.0

func WithMaxHeaderListSize(s uint32) DialOption

WithMaxHeaderListSize returns a DialOption that specifies the maximum (uncompressed) size of header list that the client is prepared to accept.

func WithMaxMsgSize DEPRECATED

func WithNoProxy <- v1.29.0

func WithNoProxy() DialOption

WithNoProxy returns a DialOption which disables the use of proxies for this ClientConn. This is ignored if WithDialer or WithContextDialer are used.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func WithPerRPCCredentials

func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption

WithPerRPCCredentials returns a DialOption which sets credentials and places auth state on each outbound RPC.

func WithReadBufferSize <- v1.7.0

func WithReadBufferSize(s int) DialOption

WithReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most for each read syscall.

The default value for this buffer is 32KB. Zero or negative values will disable read buffer for a connection so data framer can access the underlying conn directly.

func WithResolvers <- v1.27.0

func WithResolvers(rs ...resolver.Builder) DialOption

WithResolvers allows a list of resolver implementations to be registered locally with the ClientConn without needing to be globally registered via resolver.Register. They will be matched against the scheme used for the current Dial only, and will take precedence over the global registry.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func WithReturnConnectionError <- v1.30.0

func WithReturnConnectionError() DialOption

WithReturnConnectionError returns a DialOption which makes the client connection return a string containing both the last connection error that occurred and the context.DeadlineExceeded error. Implies WithBlock()

Use of this feature is not recommended. For more information, please see: https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func WithServiceConfig DEPRECATED

func WithStatsHandler <- v1.2.0

func WithStatsHandler(h stats.Handler) DialOption

WithStatsHandler returns a DialOption that specifies the stats handler for all the RPCs and underlying network connections in this ClientConn.

func WithStreamInterceptor <- v1.0.2

func WithStreamInterceptor(f StreamClientInterceptor) DialOption

WithStreamInterceptor returns a DialOption that specifies the interceptor for streaming RPCs.

func WithTimeout DEPRECATED

func WithTransportCredentials

func WithTransportCredentials(creds credentials.TransportCredentials) DialOption

WithTransportCredentials returns a DialOption which configures a connection level security credentials (e.g., TLS/SSL). This should not be used together with WithCredentialsBundle.

func WithUnaryInterceptor <- v1.0.2

func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption

WithUnaryInterceptor returns a DialOption that specifies the interceptor for unary RPCs.

func WithUserAgent

func WithUserAgent(s string) DialOption

WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.

func WithWriteBufferSize <- v1.7.0

func WithWriteBufferSize(s int) DialOption

WithWriteBufferSize determines how much data can be batched before doing a write on the wire. The corresponding memory allocation for this buffer will be twice the size to keep syscalls low. The default value for this buffer is 32KB.

Zero or negative values will disable the write buffer such that each write will be on underlying connection. Note: A Send call may not directly translate to a write.

type EmptyCallOption <- v1.4.0

type EmptyCallOption struct{}

EmptyCallOption does not alter the Call configuration. It can be embedded in another structure to carry satellite data for use by interceptors.

type EmptyDialOption <- v1.14.0

type EmptyDialOption struct{}

EmptyDialOption does not alter the dial configuration. It can be embedded in another structure to build custom dial options.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type EmptyServerOption <- v1.21.0

type EmptyServerOption struct{}

EmptyServerOption does not alter the server configuration. It can be embedded in another structure to build custom server options.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type FailFastCallOption <- v1.11.0

type FailFastCallOption struct {
	FailFast bool
}

FailFastCallOption is a CallOption for indicating whether an RPC should fail fast or not.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type ForceCodecCallOption <- v1.19.0

type ForceCodecCallOption struct {
	Codec encoding.Codec
}

ForceCodecCallOption is a CallOption that indicates the codec used for marshaling messages.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type HeaderCallOption <- v1.11.0

type HeaderCallOption struct {
	HeaderAddr *metadata.MD
}

HeaderCallOption is a CallOption for collecting response header metadata. The metadata field will be populated after the RPC completes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type MaxRecvMsgSizeCallOption <- v1.11.0

type MaxRecvMsgSizeCallOption struct {
	MaxRecvMsgSize int
}

MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message size in bytes the client can receive.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type MaxRetryRPCBufferSizeCallOption <- v1.14.0

type MaxRetryRPCBufferSizeCallOption struct {
	MaxRetryRPCBufferSize int
}

MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of memory to be used for caching this RPC for retry purposes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type MaxSendMsgSizeCallOption <- v1.11.0

type MaxSendMsgSizeCallOption struct {
	MaxSendMsgSize int
}

MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message size in bytes the client can send.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type MethodConfig DEPRECATED

type MethodDesc

type MethodDesc struct {
	MethodName string
	Handler    methodHandler
}

MethodDesc represents an RPC service’s method specification.

type MethodInfo

type MethodInfo struct {
	// Name is the method name only, without the service name or package name.
	Name string
	// IsClientStream indicates whether the RPC is a client streaming RPC.
	IsClientStream bool
	// IsServerStream indicates whether the RPC is a server streaming RPC.
	IsServerStream bool
}

MethodInfo contains the information of an RPC including its method name and type.

type OnFinishCallOption <- v1.54.0

type OnFinishCallOption struct {
	OnFinish func(error)
}

OnFinishCallOption is CallOption that indicates a callback to be called when the call completes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type PeerCallOption <- v1.11.0

type PeerCallOption struct {
	PeerAddr *peer.Peer
}

PeerCallOption is a CallOption for collecting the identity of the remote peer. The peer field will be populated after the RPC completes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type PerRPCCredsCallOption <- v1.11.0

type PerRPCCredsCallOption struct {
	Creds credentials.PerRPCCredentials
}

PerRPCCredsCallOption is a CallOption that indicates the per-RPC credentials to use for the call.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type PreparedMsg <- v1.21.0

type PreparedMsg struct {
	// contains filtered or unexported fields
}

PreparedMsg is responsible for creating a Marshalled and Compressed object.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

func (*PreparedMsg) Encode <- v1.21.0

func (p *PreparedMsg) Encode(s Stream, msg interface{}) error

Encode marshalls and compresses the message using the codec and compressor for the stream.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a gRPC server to serve RPC requests.

func NewServer

func NewServer(opt ...ServerOption) *Server

NewServer creates a gRPC server which has no service registered and has not started to accept requests yet.

func (*Server) GetServiceInfo

func (s *Server) GetServiceInfo() map[string]ServiceInfo

GetServiceInfo returns a map from service names to ServiceInfo. Service names include the package names, in the form of ..

func (*Server) GracefulStop <- v1.0.2

func (s *Server) GracefulStop()

GracefulStop stops the gRPC server gracefully. It stops the server from accepting new connections and RPCs and blocks until all the pending RPCs are finished.

func (*Server) RegisterService

func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})

RegisterService registers a service and its implementation to the gRPC server. It is called from the IDL generated code. This must be called before invoking Serve. If ss is non-nil (for legacy code), its type is checked to ensure it implements sd.HandlerType.

func (*Server) Serve

func (s *Server) Serve(lis net.Listener) error

Serve accepts incoming connections on the listener lis, creating a new ServerTransport and service goroutine for each. The service goroutines read gRPC requests and then call the registered handlers to reply to them. Serve returns when lis.Accept fails with fatal errors. lis will be closed when this method returns. Serve will return a non-nil error unless Stop or GracefulStop is called.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the Go standard library’s http.Handler interface by responding to the gRPC request r, by looking up the requested gRPC method in the gRPC server s.

The provided HTTP request must have arrived on an HTTP/2 connection. When using the Go standard library’s server, practically this means that the Request must also have arrived over TLS.

To share one port (such as 443 for https) between gRPC and an existing http.Handler, use a root http.Handler such as:

if r.ProtoMajor == 2 && strings.HasPrefix(
	r.Header.Get("Content-Type"), "application/grpc") {
	grpcServer.ServeHTTP(w, r)
} else {
	yourMux.ServeHTTP(w, r)
}

Note that ServeHTTP uses Go’s HTTP/2 server implementation which is totally separate from grpc-go’s HTTP/2 server. Performance and features may vary between the two paths. ServeHTTP does not support some gRPC features available through grpc-go’s HTTP/2 server.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func (*Server) Stop

func (s *Server) Stop()

Stop stops the gRPC server. It immediately closes all open connections and listeners. It cancels all active RPCs on the server side and the corresponding pending RPCs on the client side will get notified by connection errors.

type ServerOption

type ServerOption interface {
	// contains filtered or unexported methods
}

A ServerOption sets options such as credentials, codec and keepalive parameters, etc.

func ChainStreamInterceptor <- v1.28.0

func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption

ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor for streaming RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All stream interceptors added by this method will be chained.

func ChainUnaryInterceptor <- v1.28.0

func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption

ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor for unary RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All unary interceptors added by this method will be chained.

func ConnectionTimeout <- v1.7.3

func ConnectionTimeout(d time.Duration) ServerOption

ConnectionTimeout returns a ServerOption that sets the timeout for connection establishment (up to and including HTTP/2 handshaking) for all new connections. If this is not set, the default is 120 seconds. A zero or negative value will result in an immediate timeout.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func Creds

func Creds(c credentials.TransportCredentials) ServerOption

Creds returns a ServerOption that sets credentials for server connections.

func CustomCodec DEPRECATED

func ForceServerCodec <- v1.38.0

func ForceServerCodec(codec encoding.Codec) ServerOption

ForceServerCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.

This will override any lookups by content-subtype for Codecs registered with RegisterCodec.

See Content-Type on https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for more details. Also see the documentation on RegisterCodec and CallContentSubtype for more details on the interaction between encoding.Codec and content-subtype.

This function is provided for advanced users; prefer to register codecs using encoding.RegisterCodec. The server will automatically use registered codecs based on the incoming requests’ headers. See also https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec. Will be supported throughout 1.x.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func HeaderTableSize <- v1.25.0

func HeaderTableSize(s uint32) ServerOption

HeaderTableSize returns a ServerOption that sets the size of dynamic header table for stream.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func InTapHandle <- v1.0.5

func InTapHandle(h tap.ServerInHandle) ServerOption

InTapHandle returns a ServerOption that sets the tap handle for all the server transport to be created. Only one can be installed.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func InitialConnWindowSize <- v1.4.0

func InitialConnWindowSize(s int32) ServerOption

InitialConnWindowSize returns a ServerOption that sets window size for a connection. The lower bound for window size is 64K and any value smaller than that will be ignored.

func InitialWindowSize <- v1.4.0

func InitialWindowSize(s int32) ServerOption

InitialWindowSize returns a ServerOption that sets window size for stream. The lower bound for window size is 64K and any value smaller than that will be ignored.

func KeepaliveEnforcementPolicy <- v1.3.0

func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption

KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server.

func KeepaliveParams <- v1.3.0

func KeepaliveParams(kp keepalive.ServerParameters) ServerOption

KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.

func MaxConcurrentStreams

func MaxConcurrentStreams(n uint32) ServerOption

MaxConcurrentStreams returns a ServerOption that will apply a limit on the number of concurrent streams to each ServerTransport.

func MaxHeaderListSize <- v1.14.0

func MaxHeaderListSize(s uint32) ServerOption

MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size of header list that the server is prepared to accept.

func MaxMsgSize DEPRECATED

func MaxRecvMsgSize <- v1.4.0

func MaxRecvMsgSize(m int) ServerOption

MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive. If this is not set, gRPC uses the default 4MB.

func MaxSendMsgSize <- v1.4.0

func MaxSendMsgSize(m int) ServerOption

MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send. If this is not set, gRPC uses the default math.MaxInt32.

func NumStreamWorkers <- v1.30.0

func NumStreamWorkers(numServerWorkers uint32) ServerOption

NumStreamWorkers returns a ServerOption that sets the number of worker goroutines that should be used to process incoming streams. Setting this to zero (default) will disable workers and spawn a new goroutine for each stream.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

func RPCCompressor DEPRECATED

func RPCDecompressor DEPRECATED

func ReadBufferSize <- v1.7.0

func ReadBufferSize(s int) ServerOption

ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most for one read syscall. The default value for this buffer is 32KB. Zero or negative values will disable read buffer for a connection so data framer can access the underlying conn directly.

func StatsHandler <- v1.2.0

func StatsHandler(h stats.Handler) ServerOption

StatsHandler returns a ServerOption that sets the stats handler for the server.

func StreamInterceptor

func StreamInterceptor(i StreamServerInterceptor) ServerOption

StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the server. Only one stream interceptor can be installed.

func UnaryInterceptor

func UnaryInterceptor(i UnaryServerInterceptor) ServerOption

UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the server. Only one unary interceptor can be installed. The construction of multiple interceptors (e.g., chaining) can be implemented at the caller.

func UnknownServiceHandler <- v1.2.0

func UnknownServiceHandler(streamHandler StreamHandler) ServerOption

UnknownServiceHandler returns a ServerOption that allows for adding a custom unknown service handler. The provided method is a bidi-streaming RPC service handler that will be invoked instead of returning the “unimplemented” gRPC error whenever a request is received for an unregistered service or method. The handling function and stream interceptor (if set) have full access to the ServerStream, including its Context.

func WriteBufferSize <- v1.7.0

func WriteBufferSize(s int) ServerOption

WriteBufferSize determines how much data can be batched before doing a write on the wire. The corresponding memory allocation for this buffer will be twice the size to keep syscalls low. The default value for this buffer is 32KB. Zero or negative values will disable the write buffer such that each write will be on underlying connection. Note: A Send call may not directly translate to a write.

type ServerStream

type ServerStream interface {
	// SetHeader sets the header metadata. It may be called multiple times.
	// When call multiple times, all the provided metadata will be merged.
	// All the metadata will be sent out when one of the following happens:
	//  - ServerStream.SendHeader() is called;
	//  - The first response is sent out;
	//  - An RPC status is sent out (error or success).
	SetHeader(metadata.MD) error
	// SendHeader sends the header metadata.
	// The provided md and headers set by SetHeader() will be sent.
	// It fails if called multiple times.
	SendHeader(metadata.MD) error
	// SetTrailer sets the trailer metadata which will be sent with the RPC status.
	// When called more than once, all the provided metadata will be merged.
	SetTrailer(metadata.MD)
	// Context returns the context for this stream.
	Context() context.Context
	// SendMsg sends a message. On error, SendMsg aborts the stream and the
	// error is returned directly.
	//
	// SendMsg blocks until:
	//   - There is sufficient flow control to schedule m with the transport, or
	//   - The stream is done, or
	//   - The stream breaks.
	//
	// SendMsg does not wait until the message is received by the client. An
	// untimely stream closure may result in lost messages.
	//
	// It is safe to have a goroutine calling SendMsg and another goroutine
	// calling RecvMsg on the same stream at the same time, but it is not safe
	// to call SendMsg on the same stream in different goroutines.
	//
	// It is not safe to modify the message after calling SendMsg. Tracing
	// libraries and stats handlers may use the message lazily.
	SendMsg(m interface{}) error
	// RecvMsg blocks until it receives a message into m or the stream is
	// done. It returns io.EOF when the client has performed a CloseSend. On
	// any non-EOF error, the stream is aborted and the error contains the
	// RPC status.
	//
	// It is safe to have a goroutine calling SendMsg and another goroutine
	// calling RecvMsg on the same stream at the same time, but it is not
	// safe to call RecvMsg on the same stream in different goroutines.
	RecvMsg(m interface{}) error
}

ServerStream defines the server-side behavior of a streaming RPC.

Errors returned from ServerStream methods are compatible with the status package. However, the status code will often not match the RPC status as seen by the client application, and therefore, should not be relied upon for this purpose.

type ServerTransportStream <- v1.11.0

type ServerTransportStream interface {
	Method() string
	SetHeader(md metadata.MD) error
	SendHeader(md metadata.MD) error
	SetTrailer(md metadata.MD) error
}

ServerTransportStream is a minimal interface that a transport stream must implement. This can be used to mock an actual transport stream for tests of handler code that use, for example, grpc.SetHeader (which requires some stream to be in context).

See also NewContextWithServerTransportStream.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

func ServerTransportStreamFromContext <- v1.12.0

func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream

ServerTransportStreamFromContext returns the ServerTransportStream saved in ctx. Returns nil if the given context has no stream associated with it (which implies it is not an RPC invocation context).

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

type ServiceConfig DEPRECATED

type ServiceDesc

type ServiceDesc struct {
	ServiceName string
	// The pointer to the service interface. Used to check whether the user
	// provided implementation satisfies the interface requirements.
	HandlerType interface{}
	Methods     []MethodDesc
	Streams     []StreamDesc
	Metadata    interface{}
}

ServiceDesc represents an RPC service’s specification.

type ServiceInfo

type ServiceInfo struct {
	Methods []MethodInfo
	// Metadata is the metadata specified in ServiceDesc when registering service.
	Metadata interface{}
}

ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service.

type ServiceRegistrar <- v1.32.0

type ServiceRegistrar interface {
	// RegisterService registers a service and its implementation to the
	// concrete type implementing this interface.  It may not be called
	// once the server has started serving.
	// desc describes the service and its methods and handlers. impl is the
	// service implementation which is passed to the method handlers.
	RegisterService(desc *ServiceDesc, impl interface{})
}

ServiceRegistrar wraps a single method that supports service registration. It enables users to pass concrete types other than grpc.Server to the service registration methods exported by the IDL generated code.

type Stream DEPRECATED

type StreamClientInterceptor <- v1.0.2

type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error)

StreamClientInterceptor intercepts the creation of a ClientStream. Stream interceptors can be specified as a DialOption, using WithStreamInterceptor() or WithChainStreamInterceptor(), when creating a ClientConn. When a stream interceptor(s) is set on the ClientConn, gRPC delegates all stream creations to the interceptor, and it is the responsibility of the interceptor to call streamer.

desc contains a description of the stream. cc is the ClientConn on which the RPC was invoked. streamer is the handler to create a ClientStream and it is the responsibility of the interceptor to call it. opts contain all applicable call options, including defaults from the ClientConn as well as per-call options.

StreamClientInterceptor may return a custom ClientStream to intercept all I/O operations. The returned error must be compatible with the status package.

type StreamDesc

type StreamDesc struct {
	// StreamName and Handler are only used when registering handlers on a
	// server.
	StreamName string        // the name of the method excluding the service
	Handler    StreamHandler // the handler called for the method

	// ServerStreams and ClientStreams are used for registering handlers on a
	// server as well as defining RPC behavior when passed to NewClientStream
	// and ClientConn.NewStream.  At least one must be true.
	ServerStreams bool // indicates the server can perform streaming sends
	ClientStreams bool // indicates the client can perform streaming sends
}

StreamDesc represents a streaming RPC service’s method specification. Used on the server when registering services and on the client when initiating new streams.

type StreamHandler

type StreamHandler func(srv interface{}, stream ServerStream) error

StreamHandler defines the handler called by gRPC server to complete the execution of a streaming RPC.

If a StreamHandler returns an error, it should either be produced by the status package, or be one of the context errors. Otherwise, gRPC will use codes.Unknown as the status code and err.Error() as the status message of the RPC.

type StreamServerInfo

type StreamServerInfo struct {
	// FullMethod is the full RPC method string, i.e., /package.service/method.
	FullMethod string
	// IsClientStream indicates whether the RPC is a client streaming RPC.
	IsClientStream bool
	// IsServerStream indicates whether the RPC is a server streaming RPC.
	IsServerStream bool
}

StreamServerInfo consists of various information about a streaming RPC on server side. All per-rpc information may be mutated by the interceptor.

type StreamServerInterceptor

type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error

StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server. info contains all the information of this RPC the interceptor can operate on. And handler is the service method implementation. It is the responsibility of the interceptor to invoke handler to complete the RPC.

type Streamer <- v1.0.2

type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)

Streamer is called by StreamClientInterceptor to create a ClientStream.

type TrailerCallOption <- v1.11.0

type TrailerCallOption struct {
	TrailerAddr *metadata.MD
}

TrailerCallOption is a CallOption for collecting response trailer metadata. The metadata field will be populated after the RPC completes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

type UnaryClientInterceptor <- v1.0.2

type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error

UnaryClientInterceptor intercepts the execution of a unary RPC on the client. Unary interceptors can be specified as a DialOption, using WithUnaryInterceptor() or WithChainUnaryInterceptor(), when creating a ClientConn. When a unary interceptor(s) is set on a ClientConn, gRPC delegates all unary RPC invocations to the interceptor, and it is the responsibility of the interceptor to call invoker to complete the processing of the RPC.

method is the RPC name. req and reply are the corresponding request and response messages. cc is the ClientConn on which the RPC was invoked. invoker is the handler to complete the RPC and it is the responsibility of the interceptor to call it. opts contain all applicable call options, including defaults from the ClientConn as well as per-call options.

The returned error must be compatible with the status package.

type UnaryHandler

type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error)

UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal execution of a unary RPC.

If a UnaryHandler returns an error, it should either be produced by the status package, or be one of the context errors. Otherwise, gRPC will use codes.Unknown as the status code and err.Error() as the status message of the RPC.

type UnaryInvoker <- v1.0.2

type UnaryInvoker func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error

UnaryInvoker is called by UnaryClientInterceptor to complete RPCs.

type UnaryServerInfo

type UnaryServerInfo struct {
	// Server is the service implementation the user provides. This is read-only.
	Server interface{}
	// FullMethod is the full RPC method string, i.e., /package.service/method.
	FullMethod string
}

UnaryServerInfo consists of various information about a unary RPC on server side. All per-rpc information may be mutated by the interceptor.

type UnaryServerInterceptor

type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error)

UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info contains all the information of this RPC the interceptor can operate on. And handler is the wrapper of the service method implementation. It is the responsibility of the interceptor to invoke handler to complete the RPC.

1.5 - 生成的代码参考

Generated-code reference 生成的代码参考

https://grpc.io/docs/languages/go/generated-code/

​ 本页面描述了使用 grpc插件,即protoc-gen-go-grpc,在使用protoc编译.proto文件时生成的代码。

​ 您可以在服务定义中了解如何在.proto文件中定义gRPC服务。

Thread-safety: note that client-side RPC invocations and server-side RPC handlers are thread-safe and are meant to be run on concurrent goroutines. But also note that for individual streams, incoming and outgoing data is bi-directional but serial; so e.g. individual streams do not support concurrent reads or concurrent writes (but reads are safely concurrent with writes).

线程安全性(Thread-safety):请注意,客户端的RPC调用和服务端的RPC处理程序是线程安全(thread-safe)的,并且可以在并发的goroutine上运行。但是,请注意对于**单个流(individual streams)**而言,传入和传出的数据是双向但串行的;因此,例如,单个流不支持并发读取并发写入(但读取与写入之间是安全并发的)。

生成的服务端接口上的方法

​ 在服务端,.proto文件中的每个service Bar都会生成以下函数:

func RegisterBarServer(s *grpc.Server, srv BarServer)

​ 该应用程序可以定义BarServer接口的具体实现,并使用此函数将其注册到grpc.Server实例上(在启动服务端实例之前)。

一元方法

​ 这些方法在生成的服务接口上具有以下签名:

Foo(context.Context, *MsgA) (*MsgB, error)

​ 在这个上下文中,MsgA是从客户端发送的Protobuf消息,MsgB是从服务端返回的Protobuf消息。

服务端流式方法

​ 这些方法在生成的服务接口上具有以下签名:

Foo(*MsgA, <ServiceName>_FooServer) error

​ 在这个上下文中,MsgA是来自客户端的单个请求,<ServiceName>_FooServer参数表示MsgB消息的服务端到客户端的流。

<ServiceName>_FooServer嵌入了grpc.ServerStream和以下接口:

1
2
3
4
type <ServiceName>_FooServer interface {
	Send(*MsgB) error
	grpc.ServerStream
}

​ 服务端处理程序可以通过此参数的Send方法向客户端发送一系列的Protobuf消息。服务端到客户端的流通过处理程序方法的return语句来结束。

客户端流式方法

​ 这些方法在生成的服务接口上具有以下签名:

Foo(<ServiceName>_FooServer) error

​ 在这个上下文中,<ServiceName>_FooServer既可以用于读取客户端到服务端的消息流,也可以用于发送单个服务端响应消息。

<ServiceName>_FooServer嵌入了grpc.ServerStream和以下接口:

1
2
3
4
5
type <ServiceName>_FooServer interface {
	SendAndClose(*MsgA) error
	Recv() (*MsgB, error)
	grpc.ServerStream
}

​ 服务端处理程序可以重复调用此参数上的Recv方法,以接收来自客户端的完整消息流。一旦达到流的末尾,Recv将返回(nil, io.EOF)。通过在<ServiceName>_FooServer参数上调用SendAndClose方法,可以发送来自服务端的单个响应消息。请注意,SendAndClose方法必须且只能被调用一次。

双向流式方法

​ 这些方法在生成的服务接口上具有以下签名:

Foo(<ServiceName>_FooServer) error

​ 在这个上下文中,<ServiceName>_FooServer可用于访问客户端到服务端的消息流和服务端到客户端的消息流。<ServiceName>_FooServer嵌入了grpc.ServerStream和以下接口:

1
2
3
4
5
type <ServiceName>_FooServer interface {
	Send(*MsgA) error
	Recv() (*MsgB, error)
	grpc.ServerStream
}

​ 服务端处理程序可以重复调用此参数上的Recv方法,以读取客户端到服务端的消息流。一旦达到客户端到服务端流的末尾,Recv方法将返回(nil, io.EOF)。通过重复调用<ServiceName>_FooServer参数上的Send方法,可以发送服务端到客户端的响应消息流。服务端到客户端的流通过双向方法处理程序的return语句来结束。

生成的客户端接口上的方法

​ 对于客户端用法,.proto文件中的每个service Bar还会生成函数:func BarClient(cc *grpc.ClientConn) BarClient,该函数返回BarClient接口的具体实现(该具体实现也位于生成的.pb.go文件中)。

一元方法

​ 在生成的客户端存根(stub)上,这些方法具有以下签名:

(ctx context.Context, in *MsgA, opts ...grpc.CallOption) (*MsgB, error)

​ 在这个上下文中,MsgA是客户端发送到服务端的单个请求,MsgB包含了服务端发送回来的响应。

服务端流式方法

​ 在生成的客户端存根(stub)上,这些方法具有以下签名:

Foo(ctx context.Context, in *MsgA, opts ...grpc.CallOption) (<ServiceName>_FooClient, error)

In this context, <ServiceName>_FooClient represents the server-to-client stream of MsgB messages.

​ 在这个上下文中,<ServiceName>_FooClient表示服务端到客户端的stream,其中包含MsgB消息。

​ 这个流嵌入了grpc.ClientStream和以下接口:

1
2
3
4
type <ServiceName>_FooClient interface {
	Recv() (*MsgB, error)
	grpc.ClientStream
}

​ 这个流开始于,当客户端在存根(stub)上调用Foo方法时。然后,客户端可以重复调用返回的<ServiceName>_FooClient stream 上的Recv方法,以读取服务端到客户端的响应流。一旦完全读取了服务端到客户端的流,Recv方法将返回(nil, io.EOF)

客户端流式方法

​ 在生成的客户端存根(stub)上,这些方法具有以下签名:

Foo(ctx context.Context, opts ...grpc.CallOption) (<ServiceName>_FooClient, error)

In this context, <ServiceName>_FooClient represents the client-to-server stream of MsgA messages.

​ 在这个上下文中,<ServiceName>_FooClient表示客户端到服务端的stream,其中包含MsgA消息。

<ServiceName>_FooClient嵌入了grpc.ClientStream和以下接口:

1
2
3
4
5
type <ServiceName>_FooClient interface {
	Send(*MsgA) error
	CloseAndRecv() (*MsgB, error)
	grpc.ClientStream
}

​ 这个流开始于,当客户端在存根(stub)上调用Foo方法时。然后,客户端可以重复调用返回的<ServiceName>_FooClient流上的Send方法,来发送客户端到服务端的消息流。为了关闭客户端到服务器的流并接收来自服务器的单个响应消息,必须仅调用一次 CloseAndRecv 方法。

双向流式方法

​ 在生成的客户端存根(stub)上,这些方法具有以下签名:

Foo(ctx context.Context, opts ...grpc.CallOption) (<ServiceName>_FooClient, error)

​ 在这个上下文中,<ServiceName>_FooClient表示客户端到服务端和服务端到客户端的消息流。

<ServiceName>_FooClient嵌入了grpc.ClientStream和以下接口:

1
2
3
4
5
type <ServiceName>_FooClient interface {
	Send(*MsgA) error
	Recv() (*MsgB, error)
	grpc.ClientStream
}

​ 这个流开始于,当客户端在存根(stub)上调用Foo方法时。然后,客户端可以重复调用返回的<SericeName>_FooClient流上的Send方法,来发送客户端到服务端的消息流。客户端还可以重复调用此流上的Recv方法,来接收完整的服务端到客户端的消息流。

​ 对于服务器到客户端的流,通过流的 Recv 方法返回值为 (nil, io.EOF) 来表示流的结束。对于客户端到服务器的流,客户端可以通过在流上调用CloseSend方法来表示流结束。

包和命名空间

When the protoc compiler is invoked with --go_out=plugins=grpc:, the proto package to Go package translation works the same as when the protoc-gen-go plugin is used without the grpc plugin.

​ 当使用protoc编译器调用--go_out=plugins=grpc:时,proto package 到 Go 包的转换方式与在没有使用 grpc 插件的情况下使用 protoc-gen-go 插件时相同。

​ 例如,如果foo.proto声明其位于package foo中,则生成的foo.pb.go文件也将位于Go包foo中。