完成一個 RPC 調用

1. 產生 Demo 專案

使用已安裝的 dubbogo-cli 工具建立一個 demo 專案。

$ mkdir quickstart
$ cd quickstart
$ dubbogo-cli newDemo.
$ tree .
.
├── api
│ ├── samples_api.pb.go
│ ├── samples_api.proto
│ └── samples_api_triple.pb.go
├── go-client
│ ├── cmd
│ │ └── client.go
│ └── conf
│ └── dubbogo.yaml
├── go-server
│ ├── cmd
│ │ └── server.go
│ └── conf
│ └── dubbogo.yaml
└── go.mod

可以看到產生的專案包含一個 client 專案和一個 server 專案,以及相關的設定檔。

1.1 檢視介面描述檔 helloworld.proto

syntax = "proto3";
package api;

option go_package = "./;api";

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (User) {}
  // Sends a greeting via stream
  rpc SayHelloStream (stream HelloRequest) returns (stream User) {}
}

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

// The response message containing the greetings
message User {
  string name = 1;
  string id = 2;
  int32 age = 3;
}

在 demo 專案中,預設會產生一個介面描述檔。介面服務名稱為 api.Greeter,包含兩個 RPC 方法,輸入參數為 HelloRequest,回傳值為 User。這兩個方法分別為普通的 RPC 方法和串流 (Streaming) 類型的 RPC 方法。

1.2 (選用) 使用已安裝的編譯工具編譯 pb 介面

$ cd api
$ protoc --go_out=. --go-triple_out=. ./samples_api.proto

參數說明:`--go_out=.` 使用上面安裝的 `protoc-gen-go` 外掛程式,將檔案產生到目前目錄,`--go-triple_out=.` 使用上面安裝的 `protoc-gen-go-triple` 外掛程式,將檔案產生到目前目錄。

執行此命令後,將會產生兩個檔案,分別是 helloworld.pb(包含 proto 結構)和 helloworld_triple.pb.go(包含 triple 協定介面)。

在 demo 專案中,這兩個檔案已預先產生。修改 .proto 檔案後,再次執行命令產生即可覆蓋。

2. 發起一個 RPC 呼叫

在專案根目錄執行

$ go mod tidy

拉取最新的框架依賴

module helloworld

go 1.17

require (
dubbo.apache.org/dubbo-go/v3 v3.0.1
github.com/dubbogo/grpc-go v1.42.9
github.com/dubbogo/triple v1.1.8
google.golang.org/protobuf v1.27.1
)

require (
...
)

依序啟動伺服器和客戶端:開啟兩個終端機,分別在 go-server/cmd 和 go-client/cmd 資料夾下執行 `go run .`,即可在客戶端看到輸出

client response result: name: "Hello laurence" id: "12345" age:21

成功取得呼叫結果

3. 更多

仔細閱讀的讀者可以發現,上面範例中編寫的伺服器可以接受來自用戶端的普通 RPC 和串流 RPC 呼叫請求。目前,僅編寫了用於普通呼叫的用戶端。讀者可以嘗試根據範例程式庫中的範例編寫串流用戶端和伺服器。


最後修改日期:2023 年 1 月 2 日:增強 Dubbogo 文件 (#1800) (71c8e722740)