S-JIS[2024-11-24] 変更履歴

gRPC Rustクライアント

Rust版gRPCのクライアントのメモ。


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へ戻る / 技術メモへ戻る
メールの送信先:ひしだま