Rust版gRPCのクライアントのメモ。
|
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