gRPC library for Rust

CK CK 3788 
Created at  
343 0 0

The primary gRPC library for Rust is tonic, a production-ready implementation providing both client and server capabilities built on top of the hyper HTTP/2 library. It offers features like code generation from Protobuf definitions and asynchronous support.
 

To use tonic with gRPC in Rust, you can follow these steps:


1. Setup Your Rust Project

Create a new Rust project if you don't have one:

cargo new grpc-tonic-example
cd grpc-tonic-example

2. Add Dependencies

In your Cargo.toml, add the following dependencies:

[dependencies]
tonic = "0.10"
tokio = { version = "1", features = ["full"] }
prost = "0.11"

[build-dependencies]
tonic-build = "0.10"

3. Define the .proto File

Create a proto directory in your project and define your gRPC service in a .proto file (e.g., proto/helloworld.proto):

syntax = "proto3";

package helloworld;

// The greeting service definition.
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

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

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

4. Generate Rust Code from .proto

Create or modify build.rs to generate Rust code from your .proto file:

fn main() {
    tonic_build::compile_protos("proto/helloworld.proto")
        .unwrap_or_else(|e| panic!("Failed to compile protos: {:?}", e));
}

Run the build script to generate the code:

cargo build

The generated code will be in src/helloworld.rs.


5. Implement the Server

Create a src/server.rs file for your server logic:

use tonic::{transport::Server, Request, Response, Status};
use hello_world::greeter_server::{Greeter, GreeterServer};
use hello_world::{HelloRequest, HelloReply};

pub mod hello_world {
    tonic::include_proto!("helloworld");
}

#[derive(Debug, Default)]
pub struct MyGreeter {}

#[tonic::async_trait]
impl Greeter for MyGreeter {
    async fn say_hello(
        &self,
        request: Request<HelloRequest>,
    ) -> Result<Response<HelloReply>, Status> {
        let name = request.into_inner().name;
        let reply = HelloReply {
            message: format!("Hello, {}!", name),
        };
        Ok(Response::new(reply))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr = "[::1]:50051".parse().unwrap();
    let greeter = MyGreeter::default();

    println!("GreeterServer listening on {}", addr);

    Server::builder()
        .add_service(GreeterServer::new(greeter))
        .serve(addr)
        .await?;

    Ok(())
}

6. Implement the Client

Create a src/client.rs file for your client logic:

use hello_world::greeter_client::GreeterClient;
use hello_world::HelloRequest;

pub mod hello_world {
    tonic::include_proto!("helloworld");
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = GreeterClient::connect("http://[::1]:50051").await?;

    let request = tonic::Request::new(HelloRequest {
        name: "World".into(),
    });

    let response = client.say_hello(request).await?;

    println!("Response: {:?}", response.into_inner());

    Ok(())
}

7. Run the Server and Client

First, run the server:

cargo run --bin server

Then, in a separate terminal, run the client:

cargo run --bin client

Expected Output

  • Server Output:

    GreeterServer listening on [::1]:50051
    
  • Client Output:

    Response: HelloReply { message: "Hello, World!" }
    

This demonstrates a simple gRPC service using tonic in Rust!

Tags gRPC gRPC Example gRPC Rust Example gRPC with Rust tonic Facebook X
Comments 0
Similar posts
  1. gRPC - Open-source Universal RPC Framework developed by Google
    768
  2. Simple gRPC server based on Python
    396
  3. gRPC Server with PHP
    505
  4. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    167
  1. Rust Std misc
    372
  2. Rust Std library types
    368
  3. Rust Error Handling
    342
  4. Rust Macro Rules
    1,508
  5. Rust mechanism for defining shared behavior across different types - Traits
    1,762
  6. Rust Scoping Rules - only accessible within the block of code
    1,066
  7. Rust Generics - Generalizing types and functionalities
    1,349
  8. Rust Attributes for conditional compilation, crate, lints, mark functions, macros
    313
  9. Rust Package Management Tool - cargo
    307
  10. Rust compilation unit - Crates
    251
  11. Rust Modules - Visivility, Struct Visibility, Use Declaration, super and self, File Hierarchy
    1,889
  12. Rust functions - Methods, Closures, Capturing
    1,198
  13. Rust Flow of Control - if/else, loop. while, for and range, match, if let, let-else, while let
    335
  14. Rust Expressions
    924
  15. Rust Conversion - From, Into, TryFrom, TryInto
    1,309
  16. Rust Data Type Operations - Casting, Literals, Inference, Aliasing
    326
  17. Variable Bindings in Rust
    966
  18. Rust Custom Data Types - struct, enum, use, constants
    298
  19. Arrays and Slices in Rust
    338
  20. Tuples in Rust - a collection of values of different types
    297
  21. Literals and operators in Rust
    296
  22. Rust Data Type - What is mutable?
    256
  23. Rust Code Testing Environment without installing anything on your computer
    324
  24. Rust Thread Example
    346
  25. How do I setup Rust development environment?
    368
  26. Rust - System Programming Language invented by Graydon Hoare
    280
  27. Why America's Biggest Tech Companies Are Betting on Rust?
    287
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,019
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    251
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  16. TPU & GPU Cluster Management Tools
    245
  17. The Concept of Scaffolding in AI Agents
    234
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    222
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    221
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  30. Understanding Data Lineage
    263