简述 gRpc

gRpc 是什么?

官网简介 >gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services.

Wiki

gRPC (gRPC Remote Procedure Calls[1]) is an open source remote procedure call (RPC) system initially developed at Google. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, bidirectional streaming and flow control, blocking or nonblocking bindings, and cancellation and timeouts. It generates cross-platform client and server bindings for many languages. Most common usage scenarios include connecting services in microservices style architecture and connect mobile devices, browser clients to backend services.[2]

特点总结:

  • 谷歌开发 RPC 开源高性能框架。
  • Http/2 传输
  • Protocol Buffers 作为接口描述性语言
  • 提供身份验证、双向流和流控制、阻塞或非阻塞绑定(withBLock bind)、取消和超时等功能

调用模型

gRpc client | service

  1. 客户端(gRPC Stub)调用 A 方法,发起 RPC 调用。

  2. gRPC 客户端对请求信息使用 Protobuf 进行对象序列化压缩(IDL)。

  3. 服务端(gRPC Server)接收到请求后,解码请求体,进行业务逻辑处理并返回。

  4. gRPC 服务端对响应结果使用 Protobuf 进行对象序列化压缩(IDL)。

  5. 客户端接受到服务端响应,解码请求体。回调被调用的 A 方法,唤醒正在等待响应(阻塞)的客户端调用并返回响应结果。

简单示例 Qick Start

服务端

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

客户端调用

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.Message)

q/a

是否是异步