基于 Rust 的高性能 gRPC + REST API 服务模板项目,使用 Axum 和 Tonic 框架构建。
本项目是一个混合服务架构模板,同时提供 gRPC 和 REST API 接口,适用于需要高性能、类型安全的微服务场景。
- Web 框架: Axum 0.8
- gRPC 框架: Tonic 0.14
- 异步运行时: Tokio 1.39
- 序列化: Serde 1.0
- 日志: Tracing 0.1
- 协议定义: Protocol Buffers 3
axum-grpc-admin/
├── proto/ # Protocol Buffers 定义文件
│ └── hello.proto # Greeter 服务定义
├── src/
│ ├── main.rs # 主入口,启动 gRPC 和 REST 服务
│ ├── grpc.rs # gRPC 服务实现
│ └── rest.rs # REST API 实现
├── build.rs # 构建脚本,编译 proto 文件
├── Cargo.toml # 项目依赖配置
├── Justfile # 常用命令快捷方式
├── test.http # HTTP/gRPC 测试请求示例
└── README.md # 项目文档
- 端口:
[::1]:4000(IPv6 本地地址) - 服务:
hello.Greeter - 方法:
SayHello
service Greeter {
rpc SayHello (HelloRequest) returns (HelloResponse);
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}- 端口:
0.0.0.0:3000 - 路由:
GET /hello?name={name}
{
"message": "Hello, {name}! (by REST)"
}- Rust 1.75+
- Protocol Buffers 编译器 (protoc)
cargo build# 使用 cargo 直接运行
cargo run
# 或使用 just 命令
just dev服务启动后:
- gRPC 服务运行在
[::1]:4000 - REST API 运行在
http://0.0.0.0:3000
curl "http://localhost:3000/hello?name=michael"响应:
{
"message": "Hello, michael! (by REST)"
}或使用项目中的 test.http 文件(需要支持 gRPC 的 HTTP 客户端)。
项目使用 just 作为命令运行器:
# 开发模式运行
just dev
# 代码格式化
just fmt
# 代码检查
just lint
# 运行测试
just test
# 构建 release 版本
just release- 初始化日志系统
- 使用
tokio::spawn异步启动 gRPC 服务 - 主线程运行 REST API 服务
- 两个服务独立运行,互不阻塞
- 使用
tonic::include_proto!宏引入编译后的 proto 代码 - 实现
Greetertrait 提供服务逻辑 - 使用
#[tonic::async_trait]支持异步方法
- 使用 Axum 的
Query提取器解析查询参数 - 使用
Json响应器返回 JSON 数据 - 所有数据结构实现
Serialize和Deserializetrait
- 在编译时自动将
.proto文件编译为 Rust 代码 - 使用
tonic-prost-build生成类型安全的 gRPC 代码
- 在
proto/目录下创建新的.proto文件 - 在
build.rs中添加编译配置 - 在
src/grpc.rs中实现服务逻辑 - 在
main.rs中注册服务
- 在
src/rest.rs中定义处理函数 - 在
main.rs的路由配置中添加新路由
let app = Router::new()
.route("/hello", get(rest::hello))
.route("/your-route", get(your_handler));tonic: gRPC 框架prost: Protocol Buffers 实现axum: Web 框架tokio: 异步运行时serde: 序列化框架tracing: 结构化日志
tonic-prost-build: proto 文件编译工具
- 零拷贝: 使用 Rust 的所有权系统避免不必要的数据拷贝
- 异步 I/O: 基于 Tokio 的高效异步运行时
- 类型安全: 编译时类型检查,避免运行时错误
- 低内存占用: Rust 的内存管理无需 GC
MIT License
欢迎提交 Issue 和 Pull Request!