gRPC

gRPC 是 Google 開發的高效能、開源的遠程過程調用(RPC)框架。

概述

gRPC 框架基於客戶端-伺服器模型的遠程過程調用。客戶端應用程式可以直接調用伺服器應用程式上的方法,就像調用本地物件一樣。

gRPC 是一種契約式嚴格方法,客戶端和伺服器都需要存取相同的 schema 定義。

Protocol Buffers (Protobuf)

gRPC 使用 Protocol Buffers 作為介面定義語言(IDL)和訊息交換格式。

syntax = "proto3";

message <NameOfTheMessage> {
    <data-type> name_of_field_1 = tag_1;
    ...
    <data-type> name_of_field_N = tag_N;
}

四種通訊類型

類型說明模式
Unary一對一一個 request 對一個 response
Client-side streaming多對一Client 送多個請求,Server 回一個 response
Server-side streaming一對多Client 送一個請求,Server 回多個 response
Bidirectional streaming多對多雙向串流

Unary RPC

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

Client-side Streaming

service RouteGuide {
  rpc RecordRoute (stream Point) returns (RouteSummary);
}

Server-side Streaming

service RouteGuide {
  rpc ListFeatures (Rectangle) returns (stream Feature);
}

Bidirectional Streaming

service RouteGuide {
  rpc RouteChat (stream RouteNote) returns (stream RouteNote);
}

CLI 工具

安裝 protoc 插件

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

安裝 gRPC

go get -u google.golang.org/grpc

生成程式碼

protoc --go_out=./ --go_opt=paths=source_relative \
       --go-grpc_out=./ --go-grpc_opt=paths=source_relative \
       ./helloworld.proto

gRPC vs REST

特性gRPCREST
協定HTTP/2HTTP/1.1 或 HTTP/2
資料格式Protocol Buffers(二進制)JSON/XML(文字)
契約嚴格(.proto 檔案)彈性(OpenAPI 可選)
串流原生支援雙向串流有限支援
瀏覽器支援需要 gRPC-Web原生支援
效能中等

適用場景

  • 微服務之間的通訊
  • 低延遲、高吞吐量的系統
  • 需要雙向串流的應用
  • 多語言服務互操作

相關主題