使用 Rust 构建功能完整的 gRPC API

作者:API传播员 · 2025-09-25 · 阅读时间:6分钟

本文将展示如何使用 Rust 构建一个功能完善的 gRPC API。通过本教程,您将学习如何定义服务协议、编译 Protobuf 文件、实现服务器和客户端,以及测试 gRPC 服务。


先决条件

在开始之前,请确保您已经安装了以下工具和环境:

  • Rust 编译器及其工具链(推荐使用最新稳定版)
  • Protobuf 编译器(protoc
  • cargo 包管理器
  • 基本的 Rust 编程知识

第一步:创建项目脚手架

首先,选择一个目录作为项目的工作目录,并使用以下命令创建一个新的 Rust crate:

cargo new demo

接下来,进入项目目录,为后续步骤准备好代码结构。


第二步:定义服务协议

在本教程中,我们将创建一个服务,用于跟踪杂货店的库存。该服务支持以下功能:

  • 查看和创建商品
  • 更新库存数量和价格
  • 观察库存变化(支持流式调用)

我们将通过 Protobuf 定义服务协议。首先,创建一个 proto/ 目录,用于存放 .proto 文件:

mkdir proto

然后,在 proto/ 目录下创建 store.proto 文件,定义服务和消息类型。以下是一个示例:

message WatchRequest {
string filter = 1;
}

package store;

service Inventory {
rpc Add(Item) returns (Response);
rpc Remove(ItemId) returns (Response);
rpc Get(ItemId) returns (Item);
rpc UpdateQuantity(UpdateRequest) returns (Response);
rpc UpdatePrice(UpdateRequest) returns (Response);
rpc Watch(WatchRequest) returns (stream Item);
}

message Item {
string id = 1;
string name = 2;
int32 quantity = 3;
float price = 4;
}

message ItemId {
string id = 1;
}

message UpdateRequest {
string id = 1;
int32 quantity = 2;
float price = 3;
}

message Response {
string message = 1;
}

message WatchRequest {
string filter = 1;
}

第三步:编译 Protobuf 文件

定义好服务协议后,我们需要编译 .proto 文件以生成 Rust 的客户端和服务器代码。为此,我们需要添加以下依赖到 Cargo.toml 文件中:

[dependencies]
tonic = "0.7"
prost = "0.11"

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

接着,创建一个 build.rs 文件,用于在构建时自动编译 .proto 文件:

fn main() {
    tonic_build::configure()
        .build_server(true)
        .build_client(true)
        .out_dir("src/")
        .compile(&["proto/store.proto"], &["proto"])
        .unwrap();
}

运行以下命令以生成代码:

cargo build

此时,src/ 目录下将生成 store.rs 文件,其中包含客户端和服务器的代码。


第四步:实现服务器

接下来,我们需要实现服务器端逻辑。创建一个新的文件 src/server.rs,并引入必要的模块:

use tonic::{transport::Server, Request, Response, Status};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;

mod store {
    tonic::include_proto!("store");
}use store::inventory_server::{Inventory, InventoryServer};
use store::{Item, ItemId, Response as StoreResponse, UpdateRequest};

定义库存管理结构

我们将使用一个线程安全的 HashMap 作为内存中的库存存储:

#[derive(Default)]
pub struct StoreInventory {
    inventory: Arc<Mutex<HashMap>>,
}

实现服务方法

以下是 Inventory 服务的部分方法实现:

添加商品

#[tonic::async_trait]
impl Inventory for StoreInventory {
    async fn add(
        &self,
        request: Request,
    ) -> Result<Response, Status> {
        let item = request.into_inner();
        let mut inventory = self.inventory.lock().unwrap();

        if inventory.contains_key(&item.id) {
            return Err(Status::already_exists("Item already exists"));
        }        inventory.insert(item.id.clone(), item);
        Ok(Response::new(StoreResponse {
            message: "Item added successfully".to_string(),
        }))
    }
}

删除商品

async fn remove(
    &self,
    request: Request,
) -> Result<Response, Status> {
    let id = request.into_inner().id;
    let mut inventory = self.inventory.lock().unwrap();

    if inventory.remove(&id).is_some() {
        Ok(Response::new(StoreResponse {
            message: "Item removed successfully".to_string(),
        }))
    } else {
        Err(Status::not_found("Item not found"))
    }
}

更新库存数量

async fn update_quantity(
    &self,
    request: Request,
) -> Result<Response, Status> {
    let update = request.into_inner();
    let mut inventory = self.inventory.lock().unwrap();

    if let Some(item) = inventory.get_mut(&update.id) {
        item.quantity += update.quantity;
        Ok(Response::new(StoreResponse {
            message: "Quantity updated successfully".to_string(),
        }))
    } else {
        Err(Status::not_found("Item not found"))
    }
}

完成所有方法后,启动服务器:

#[tokio::main]
async fn main() -> Result<(), Box> {
    let addr = "[::1]:50051".parse().unwrap();
    let inventory = StoreInventory::default();

    Server::builder()
        .add_service(InventoryServer::new(inventory))
        .serve(addr)
        .await?;    Ok(())
}

第五步:实现客户端

为了测试服务器,我们需要实现一个简单的命令行客户端。以下是客户端的主要逻辑:

添加商品

async fn add_item(client: &mut InventoryClient, id: &str, name: &str, quantity: i32, price: f32) {
    let item = Item {
        id: id.to_string(),
        name: name.to_string(),
        quantity,
        price,
    };

    let response = client.add(Request::new(item)).await.unwrap();
    println!("Response: {}", response.into_inner().message);
}

启动客户端

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

    add_item(&mut client, "1", "Apple", 100, 1.5).await;    Ok(())
}

第六步:测试服务

运行服务器后,使用客户端发送请求以测试服务功能。例如:

cargo run --bin server
cargo run --bin client

您可以尝试添加、删除、更新商品,并观察服务器的响应。


总结

通过本教程,您已经学会了如何使用 Rust 构建一个完整的 gRPC API,包括服务协议定义、Protobuf 编译、服务器实现和客户端测试。接下来,您可以尝试添加更多功能,例如 TLS 加密和身份验证,以提升服务的安全性

原文链接: https://konghq.com/blog/engineering/building-grpc-apis-with-rust