S-JIS[2024-11-24/2026-03-12] 変更履歴

gRPC Rust(tonic 0.12)クライアント

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に以下の設定を追加する。

プロジェクト/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を用意する。

プロジェクト/build.rs:

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tonic_build::compile_protos("proto/example.proto")?;
    Ok(())
}

protoファイル

C++版gRPCサーバーのprotoファイルと同じものを使用する。

プロジェクト/proto/example.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);
}

Rustソースファイル

src/bin/int64pair_client.rs

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

リクエストを受け付けるC++版gRPCサーバーの例


gRPC Rustへ戻る / gRPCへ戻る / 技術メモへ戻る
メールの送信先:ひしだま