tonic 0.12で作る、Rust版gRPCのクライアントのメモ。
|
Rustのtonic 0.12(古い)でgRPCのクライアントを作ってみる。
→tonic 0.14の例 [2026-03-12]
tonic 0.12でgRPCのクライアントを作ってみる。
この例では、gRPCサーバーはC++版。
tonicを使うために、Cargo.tomlに以下の設定を追加する。
〜
[dependencies]
prost = "0.13.3"
tonic = "0.12.3"
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
tonic-build = "0.12.3"
tonic本体と、ビルドに使用するtonic-buildを追加する。
また、protobufをビルドして生成された構造体を使う為にprostを使用する。
それと、tokioも追加しておく。
そして、protoファイルをビルドする為のbuild.rsを用意する。
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::compile_protos("proto/example.proto")?;
Ok(())
}
C++版gRPCサーバーのprotoファイルと同じものを使用する。
syntax = "proto3";
package example.grpc;
message Int64PairRequest {
int64 first_value = 1;
int64 second_value = 2;
}
message Int64PairResponse {
int64 first_value = 1;
int64 second_value = 2;
}
service ExampleService {
rpc SendInt64Pair(Int64PairRequest) returns (Int64PairResponse);
}
pub mod example {
pub mod grpc {
tonic::include_proto!("example.grpc");
}
}
tonic::include_proto!マクロの引数には、protoファイルに定義されたパッケージ名を指定する。
use example::grpc::example_service_client::ExampleServiceClient; use example::grpc::Int64PairRequest; use tonic::transport::Channel;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let port = 50051;
let url = format!("http://localhost:{port}");
println!("address = {}", url);
let mut client = ExampleServiceClient::connect(url).await?;
let request = tonic::Request::new(Int64PairRequest {
first_value: 123,
second_value: 456,
});
let response = client.send_int64_pair(request).await?;
println!("response = {:?}", response.into_inner());
Ok(())
}
protoファイルではプロシージャー名はCamelCaseで書かれているが、Rustに変換されるとsnake_caseになる。
src/binの下にあるrsファイルは、Cargoのrunに--binオプションを付けて実行できる。
cd プロジェクト cargo run --bin int64pair_client