# Rust-Api **Repository Path**: LiuYj_Admin/rust-api ## Basic Information - **Project Name**: Rust-Api - **Description**: No description available - **Primary Language**: Rust - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-01-14 - **Last Updated**: 2026-01-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Rust 通用系统后端架构 基于《Rust 通用系统后端架构设计大纲及解释.md》文档实现的Rust后端系统架构。 ## 📖 快速导航 - **[快速启动指南](docs/QUICKSTART(快速启动指南).md)** - 详细的运行步骤和测试方法 - **[项目结构文档](docs/PROJECT_STRUCTURE(项目结构).md)** - 详细的模块结构和职责说明 - **[架构分析文档](docs/ARCHITECTURE_ANALYSIS(架构分析与依赖关系).md)** - 依赖关系和作用关系详细分析 - **[依赖关系图](docs/DEPENDENCY_GRAPH(依赖关系图).md)** - 图形化的依赖关系展示 - **[开发指南](docs/DEVELOPMENT_GUIDE(开发指导).md)** - 完整的开发流程和最佳实践 - **[配置说明](docs/CONFIGURATION(配置管理说明).md)** - 配置管理和环境变量使用 - **[模块化与文档审查报告](docs/MODULARIZATION_AND_DOCUMENTATION_REVIEW(模块化与文档审查报告).md)** - 模块化/原子化检查与文档充分性评估 - **[预留模块使用指南](docs/RESERVED_MODULES_GUIDE(预留模块使用指南).md)** - BaseRepository、BaseService 使用说明 - **[宏使用示例](api-host/src/routes/MACROS_EXAMPLES(路由宏使用示例).md)** - 路由宏的使用方法和完整示例 - [项目结构](#项目结构) - 了解项目目录结构 - [快速开始](#快速开始) - 安装依赖和运行项目 - [API端点](#api端点) - 查看可用的 API 接口 ## 项目结构 ``` Rust-Api/ ├── Cargo.toml # 工作空间配置 ├── README.md ├── api-host/ # API入口项目 │ ├── Cargo.toml │ ├── config/ │ │ └── app.toml # 应用配置文件 │ └── src/ │ ├── main.rs # 程序入口 │ ├── app.rs # 应用组装 │ ├── openapi.rs # OpenAPI文档定义 │ ├── routes/ # 路由模块 │ │ ├── sys_user/ # 系统用户路由 │ │ └── sys_role/ # 系统角色路由 │ └── middleware/ # 中间件模块 │ └── auth.rs # 认证中间件 ├── infrastructure/ # 基础设施层 │ ├── Cargo.toml │ └── src/ │ ├── config.rs # 配置管理 │ ├── logging.rs # 日志初始化 │ ├── database.rs # 数据库连接池(Diesel) │ ├── cache.rs # 多级缓存服务 │ ├── crypto.rs # 密码服务实现 │ ├── http_client.rs # HTTP客户端 │ ├── models/ # 业务模型(Diesel 模型) │ │ ├── sys_user.rs # 系统用户模型 │ │ └── sys_role.rs # 系统角色模型 │ └── repository/ # Repository实现 │ ├── sys_user/ # 用户Repository │ └── sys_role/ # 角色Repository ├── application/ # 应用服务层 │ ├── Cargo.toml │ └── src/ │ ├── repository.rs # Repository接口定义 │ └── service/ # 服务实现 │ ├── sys_user/ # 用户服务 │ └── sys_role/ # 角色服务 └── shared/ # 共享代码 ├── Cargo.toml └── src/ ├── error.rs # 统一错误类型 ├── types.rs # 共享类型定义 ├── result.rs # API响应格式 └── crypto.rs # 密码服务接口 ``` ## 架构特点 - ✅ **模块化设计**:清晰的分层结构,职责分离 - ✅ **类型安全**:充分利用Rust类型系统和Diesel的编译时查询验证 - ✅ **异步优先**:基于Tokio异步运行时 - ✅ **高性能**:零成本抽象,无GC - ✅ **可扩展**:支持业务模块快速接入 - ✅ **Diesel ORM**:使用Diesel作为唯一ORM,Migration First模式 - ✅ **雪花ID**:统一使用雪花ID(i64)作为实体ID ## 快速开始 ### 前置要求 #### 必需依赖 - **Rust 1.75+**:Rust 编程语言和工具链 - **PostgreSQL**:数据库服务器 - **Redis**:缓存服务器 #### 系统构建工具(必需) 项目使用了 `native-tls` 特性,需要系统级的构建工具: **Windows:** - **CMake**:用于构建 TLS 库(aws-lc-sys) ```powershell # 方法1: 使用 winget 安装 winget install Kitware.CMake # 方法2: 使用 Chocolatey choco install cmake # 方法3: 使用 Scoop scoop install cmake # 方法4: 下载安装包 # 访问 https://cmake.org/download/ 下载并安装 ``` - **Microsoft C++ Build Tools** 或 **Visual Studio**(包含 MSVC 编译器) ```powershell # 安装 Visual Studio Build Tools winget install Microsoft.VisualStudio.2022.BuildTools # 或安装 Visual Studio Community(包含完整 IDE) winget install Microsoft.VisualStudio.2022.Community ``` > **注意**:安装时必须勾选"使用 C++ 的桌面开发"工作负载 **Linux (Ubuntu/Debian):** ```bash sudo apt-get update sudo apt-get install -y \ build-essential \ cmake \ pkg-config \ libssl-dev \ libpq-dev ``` **Linux (Fedora):** ```bash sudo dnf install \ gcc \ gcc-c++ \ cmake \ pkg-config \ openssl-devel \ postgresql-devel ``` **macOS:** ```bash # 安装 Xcode Command Line Tools xcode-select --install # 使用 Homebrew 安装其他依赖 brew install cmake openssl pkg-config postgresql ``` #### 替代方案:使用 rustls(避免 cmake 依赖) 如果不想安装 cmake,可以修改 `Cargo.toml` 使用 `rustls` 替代 `native-tls`: ```toml # 修改 reqwest 配置 reqwest = { version = "0.13.1", features = ["json", "rustls-tls"], default-features = false } ``` ### 安装依赖 ```bash # 1. 安装Rust(如果还没有) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source ~/.cargo/env # Linux/macOS # Windows: 重启命令行或手动添加到 PATH # 2. 验证安装 rustc --version cargo --version cmake --version # 验证 cmake 已安装(如果使用 native-tls) # 3. 克隆项目 cd Rust-Api # 4. 构建项目 cargo build ``` ### 常见构建问题 #### 问题1: 缺少 cmake **错误信息**: ``` error: failed to run custom build command for `aws-lc-sys v0.35.0` Missing dependency: cmake ``` **解决方案**: - Windows: 安装 CMake(见上方安装说明) - Linux: `sudo apt-get install cmake` 或 `sudo dnf install cmake` - macOS: `brew install cmake` #### 问题2: 缺少 C++ 编译器 **错误信息**: ``` error: linker `link.exe` not found ``` **解决方案**: - Windows: 安装 Visual Studio Build Tools(见上方安装说明) - Linux: `sudo apt-get install build-essential` - macOS: `xcode-select --install` #### 问题3: 缺少 OpenSSL 开发库 **错误信息**: ``` error: failed to run custom build command for `openssl-sys` ``` **解决方案**: - Linux: `sudo apt-get install libssl-dev` 或 `sudo dnf install openssl-devel` - macOS: `brew install openssl` - Windows: - 如果使用 `bundled` 特性(项目默认配置),可能需要安装 **Strawberry Perl**(见问题4) - 或者安装 PostgreSQL 客户端库并设置环境变量 `PQ_LIB_DIR` - 或者使用系统自带的 schannel(需要修改配置) #### 问题4: 缺少 Perl(Windows)- 构建 OpenSSL 相关依赖时 **问题原因**: - 项目使用了 `openssl-sys` 的 `vendored` 特性(在 `Cargo.toml` 中配置) - 当使用 `bundled` 特性编译 PostgreSQL 客户端库(`pq-sys`)时,需要 Perl 来构建 OpenSSL - OpenSSL 的构建脚本(Configure)需要 Perl 来执行 **错误信息**: ``` error: failed to run custom build command for `openssl-sys` Can't locate ExtUtils/MakeMaker.pm ``` 或 ``` error: failed to run custom build command for `openssl-sys` perl: command not found ``` **解决方案**: ```powershell # 1. 安装 Strawberry Perl winget install StrawberryPerl.StrawberryPerl # 2. 安装后重启命令行或重新加载环境变量 # 确保 Perl 已添加到 PATH 环境变量 # 3. 验证 Perl 安装 perl --version # 4. 清理构建缓存并重新构建 cargo clean cargo build ``` **为什么需要 Perl?** - OpenSSL 的构建系统使用 Perl 脚本(Configure)来生成 Makefile - `openssl-sys` 的 `vendored` 特性会在编译时自动构建 OpenSSL,需要 Perl 来执行构建脚本 - 项目配置了 `pq-sys` 的 `bundled` 特性和 `openssl-sys` 的 `vendored` 特性,这些都需要 Perl **替代方案**: 如果不想安装 Perl,可以: 1. 安装 PostgreSQL 客户端库,并设置环境变量 `PQ_LIB_DIR` 2. 修改 `Cargo.toml`,移除 `bundled` 和 `vendored` 特性(需要系统已安装 PostgreSQL 和 OpenSSL) ### 配置 配置文件已存在于 `api-host/config/app.toml`,默认配置如下: ```toml [database] master_url = "postgresql://postgres:postgres@localhost:5432/rust_api" slave_urls = [] max_connections = 50 [redis] url = "redis://localhost:6379" max_connections = 10 [server] host = "0.0.0.0" port = 3000 [logging] level = "info" format = "json" ``` 如需修改配置,请编辑 `api-host/config/app.toml` 文件。 ### 启动依赖服务 在运行应用之前,需要先启动 PostgreSQL 和 Redis 服务。 #### 方式一:使用 Docker Compose(推荐) 项目已包含 `docker-compose.yml` 文件,可以快速启动数据库和 Redis: ```powershell # Windows PowerShell cd Rust-Api docker-compose up -d # Linux/macOS cd Rust-Api docker-compose up -d ``` 这将启动: - PostgreSQL(端口 5432) - Redis(端口 6379) #### 方式二:手动安装 **Windows:** ```powershell # 安装 PostgreSQL winget install PostgreSQL.PostgreSQL # 安装 Redis(或使用 Docker) docker run -d --name redis -p 6379:6379 redis:7-alpine ``` **Linux (Ubuntu/Debian):** ```bash sudo apt-get update sudo apt-get install -y postgresql redis-server sudo systemctl start postgresql redis ``` **macOS:** ```bash brew install postgresql redis brew services start postgresql redis ``` 创建数据库: ```bash # 使用 psql psql -U postgres CREATE DATABASE rust_api; \q ``` ### 数据库迁移(使用 Diesel) 项目使用 **Diesel ORM** 的 **Migration First** 模式,**不会自动创建表结构**。在首次运行应用之前,必须手动运行数据库迁移来创建表结构。 #### 1. 安装 Diesel CLI ```bash # 安装 diesel-cli(仅支持 PostgreSQL) cargo install diesel_cli --no-default-features --features postgres ``` **Windows 注意事项**: - 如果遇到 `libpq.lib` 链接错误,项目已配置使用 `bundled` 特性,会自动编译 PostgreSQL 客户端库 - 这需要 CMake 和 C++ 编译器(见上方"系统构建工具"部分) - 或者安装 PostgreSQL 并设置环境变量 `PQ_LIB_DIR`(例如:`C:\Program Files\PostgreSQL\16\lib`) #### 2. 运行数据库迁移 ```bash # Windows PowerShell # 设置数据库连接URL $env:DATABASE_URL="postgresql://postgres:postgres@localhost:5432/rust_api" # 运行所有待执行的迁移 diesel migration run # Linux/macOS export DATABASE_URL="postgresql://postgres:postgres@localhost:5432/rust_api" diesel migration run ``` **迁移说明**: - 迁移文件位于 `migrations/` 目录 - 每个迁移包含 `up.sql`(创建表)和 `down.sql`(回滚) - 项目已包含以下迁移: - `20250101000000_create_sys_user_table` - 创建系统用户表 - `20250101000001_create_sys_role_table` - 创建系统角色表 #### 3. 验证迁移 ```bash # 连接到数据库验证表是否创建成功 psql -U postgres -d rust_api # 查看所有表 \dt # 应该看到 sys_user 和 sys_role 表 # 退出 \q ``` #### 4. 回滚迁移(如需要) ```bash # 回滚最后一次迁移 diesel migration revert # 查看迁移状态 diesel migration list ``` **重要提示**: - ⚠️ **项目启动前必须先运行迁移**,否则会因表不存在而报错 - ⚠️ **Diesel 采用 Migration First 模式**,不支持自动创建表 - ⚠️ `infrastructure/src/schema.rs` 中的 `diesel::table!` 宏只是**描述**表结构,不用于创建表 - ✅ 迁移文件可以版本控制,便于团队协作和部署 更多详细信息请参考: - **[migrations/README.md](migrations/README.md)** - 迁移详细说明与表创建指南 ### 运行 #### 开发模式 ```bash # 确保数据库和 Redis 已启动 cd Rust-Api cargo run --bin api-host ``` 服务启动后,你应该看到类似输出: ``` 日志系统初始化完成 配置加载成功 数据库连接池初始化成功 缓存服务初始化成功 雪花ID生成器初始化成功: machine_id=37 服务器启动在: 0.0.0.0:3000 ``` **启动流程说明**: 1. **日志系统初始化** - 最先初始化,确保后续日志可以输出 2. **配置加载** - 从 `config/app.toml` 或环境变量加载配置 3. **数据库连接池初始化** - 初始化 PostgreSQL 连接池(**需要先运行迁移创建表**) 4. **缓存服务初始化** - 初始化 Redis 连接和本地缓存 5. **雪花ID生成器初始化** - 初始化全局雪花ID生成器(基于 ferroid 库) 6. **HTTP服务器启动** - 启动 Axum HTTP 服务器,监听指定端口 #### 发布模式 ```bash # 构建发布版本 cargo build --release # 运行 # Windows .\target\release\api-host.exe # Linux/macOS ./target/release/api-host ``` ### 测试 API 服务启动后,可以通过以下方式测试: #### 1. 健康检查 ```powershell # PowerShell - 访问 Swagger UI(如果启用) Start-Process http://localhost:3000/swagger-ui # 或使用浏览器访问 # http://localhost:3000/swagger-ui ``` ```bash # curl - 访问 Swagger UI(如果启用) curl http://localhost:3000/swagger-ui ``` #### 2. 使用测试脚本 项目包含 `test-api.ps1` 脚本(Windows PowerShell): ```powershell cd Rust-Api .\test-api.ps1 ``` #### 3. 创建系统用户示例 ```powershell # PowerShell $body = @{ username = "testuser" email = "test@example.com" password = "123456" } | ConvertTo-Json Invoke-WebRequest -Uri http://localhost:3000/api/sys/users ` -Method POST ` -ContentType "application/json" ` -Body $body ``` ```bash # curl curl -X POST http://localhost:3000/api/sys/users \ -H "Content-Type: application/json" \ -d '{"username":"testuser","email":"test@example.com","password":"123456"}' ``` ### 详细运行指南 更多详细的运行说明、故障排查和测试方法,请参考: - **[QUICKSTART(快速启动指南).md](docs/QUICKSTART(快速启动指南).md)** - 快速启动详细指南 ### 单元测试 ```bash # 运行所有测试 cargo test # 运行特定模块的测试 cargo test --package shared ``` ## API端点 ### 系统用户管理(sys_user) - `POST /api/sys/users` - 创建系统用户 - `GET /api/sys/users` - 分页查询系统用户 - `GET /api/sys/users/{id}` - 获取用户信息 - `PUT /api/sys/users/{id}` - 更新用户 - `DELETE /api/sys/users/{id}` - 软删除用户 ### 系统角色管理(sys_role) - `POST /api/sys/roles` - 创建系统角色 - `GET /api/sys/roles` - 分页查询系统角色 - `GET /api/sys/roles/{id}` - 获取角色信息 - `PUT /api/sys/roles/{id}` - 更新角色 - `DELETE /api/sys/roles/{id}` - 软删除角色 ### API文档 - `GET /swagger-ui` - Swagger UI 文档界面(需在配置中启用) - `GET /api-docs/openapi.json` - OpenAPI JSON 规范 > **注意**:Swagger UI 默认在开发环境启用,生产环境建议禁用。配置方法见 [CONFIGURATION(配置管理说明).md](docs/CONFIGURATION(配置管理说明).md) ## 开发指南 ### 添加新业务模块 1. 在 `infrastructure` 中定义 Model、Schema、Repository(trait + 实现) 2. 在 `application` 中实现 Service 与 Command 3. 在 `api-host` 中添加路由与 Handler,并注册到 OpenAPI 4. 使用 `diesel migration generate` 创建迁移并执行 详见 [DEVELOPMENT_GUIDE(开发指导).md](docs/DEVELOPMENT_GUIDE(开发指导).md)。 ### 错误处理 使用 `shared::AppError` 统一错误类型,通过 `Result` 传播错误。 ### 日志 使用 `tracing` 宏记录日志: ```rust use tracing::{info, error, debug}; info!("处理请求"); error!(error = ?e, "操作失败"); ``` ## 发布与部署 ### 发布构建(Release Build) #### 优化构建 ```bash # 标准发布构建 cargo build --release # 优化构建(启用 LTO 和更多优化) RUSTFLAGS="-C target-cpu=native -C link-arg=-s" cargo build --release # 或者修改 Cargo.toml 添加优化配置 ``` 在 `Cargo.toml` 中添加优化配置: ```toml [profile.release] opt-level = 3 # 最大优化级别 lto = true # 链接时优化 codegen-units = 1 # 单个代码生成单元,更好的优化 strip = true # 移除调试符号(减小二进制大小) panic = "abort" # 直接终止而不是展开(减小二进制大小) ``` #### 构建产物 构建完成后,二进制文件位于: - Linux/macOS: `target/release/api-host` - Windows: `target/release/api-host.exe` #### 检查二进制大小 ```bash # Linux/macOS ls -lh target/release/api-host # Windows dir target\release\api-host.exe ``` ### 本地部署 #### 1. 准备配置文件 创建生产环境配置文件 `api-host/config/production.toml`: ```toml [database] master_url = "postgresql://user:password@localhost:5432/rust_api" max_connections = 100 min_connections = 10 acquire_timeout_secs = 30 idle_timeout_secs = 600 [redis] url = "redis://localhost:6379" max_connections = 50 connection_timeout_secs = 5 [server] host = "0.0.0.0" port = 8080 workers = 4 # 工作线程数(建议设置为 CPU 核心数) [logging] level = "info" format = "json" file_path = "/var/log/rust-api/app.log" max_file_size_mb = 100 max_files = 10 ``` #### 2. 设置环境变量 ```bash # Linux/macOS export RUST_LOG=info export CONFIG_PATH=/path/to/config/production.toml # Windows set RUST_LOG=info set CONFIG_PATH=C:\path\to\config\production.toml ``` #### 3. 运行应用 ```bash # 直接运行 ./target/release/api-host # 后台运行(Linux/macOS) nohup ./target/release/api-host > /var/log/rust-api/stdout.log 2>&1 & # 使用 screen(Linux) screen -S rust-api ./target/release/api-host # 按 Ctrl+A 然后 D 退出 screen # 使用 tmux(Linux) tmux new -s rust-api ./target/release/api-host # 按 Ctrl+B 然后 D 退出 tmux ``` ### Docker 部署 #### 1. 创建 Dockerfile 创建 `Dockerfile`: ```dockerfile # 构建阶段 FROM rust:1.75-slim as builder WORKDIR /app # 安装构建依赖 RUN apt-get update && apt-get install -y \ cmake \ pkg-config \ libssl-dev \ libpq-dev \ && rm -rf /var/lib/apt/lists/* # 复制依赖文件 COPY Cargo.toml Cargo.lock ./ COPY shared ./shared COPY application ./application COPY infrastructure ./infrastructure COPY api-host ./api-host # 构建发布版本 RUN cargo build --release # 运行阶段 FROM debian:bookworm-slim WORKDIR /app # 安装运行时依赖 RUN apt-get update && apt-get install -y \ ca-certificates \ libssl3 \ libpq5 \ && rm -rf /var/lib/apt/lists/* # 从构建阶段复制二进制文件 COPY --from=builder /app/target/release/api-host /usr/local/bin/api-host # 复制配置文件 COPY api-host/config /app/config # 暴露端口 EXPOSE 8080 # 设置环境变量 ENV RUST_LOG=info ENV CONFIG_PATH=/app/config/production.toml # 运行应用 CMD ["api-host"] ``` #### 2. 创建 docker-compose.yml 创建 `docker-compose.yml`: ```yaml version: '3.8' services: api: build: context: . dockerfile: Dockerfile ports: - "8080:8080" environment: - RUST_LOG=info - CONFIG_PATH=/app/config/production.toml volumes: - ./api-host/config:/app/config:ro - ./logs:/var/log/rust-api depends_on: - postgres - redis restart: unless-stopped networks: - rust-api-network postgres: image: postgres:16-alpine environment: POSTGRES_DB: rust_api POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - postgres_data:/var/lib/postgresql/data ports: - "5432:5432" networks: - rust-api-network restart: unless-stopped redis: image: redis:7-alpine ports: - "6379:6379" volumes: - redis_data:/data networks: - rust-api-network restart: unless-stopped command: redis-server --appendonly yes volumes: postgres_data: redis_data: networks: rust-api-network: driver: bridge ``` #### 3. 构建和运行 ```bash # 构建镜像 docker build -t rust-api:latest . # 使用 docker-compose docker-compose up -d # 查看日志 docker-compose logs -f api # 停止服务 docker-compose down # 停止并删除数据卷 docker-compose down -v ``` ### 生产环境部署 #### Linux 系统服务(systemd) 创建 systemd 服务文件 `/etc/systemd/system/rust-api.service`: ```ini [Unit] Description=Rust API Service After=network.target postgresql.service redis.service Requires=postgresql.service redis.service [Service] Type=simple User=rust-api Group=rust-api WorkingDirectory=/opt/rust-api ExecStart=/opt/rust-api/api-host Restart=always RestartSec=10 StandardOutput=journal StandardError=journal SyslogIdentifier=rust-api # 环境变量 Environment="RUST_LOG=info" Environment="CONFIG_PATH=/opt/rust-api/config/production.toml" # 安全设置 NoNewPrivileges=true PrivateTmp=true ProtectSystem=strict ProtectHome=true ReadWritePaths=/var/log/rust-api # 资源限制 LimitNOFILE=65536 LimitNPROC=4096 [Install] WantedBy=multi-user.target ``` 部署步骤: ```bash # 1. 创建用户和目录 sudo useradd -r -s /bin/false rust-api sudo mkdir -p /opt/rust-api/{config,logs} sudo chown -R rust-api:rust-api /opt/rust-api # 2. 复制文件 sudo cp target/release/api-host /opt/rust-api/ sudo cp api-host/config/production.toml /opt/rust-api/config/ sudo chmod +x /opt/rust-api/api-host # 3. 创建服务文件 sudo cp rust-api.service /etc/systemd/system/ # 4. 重新加载 systemd sudo systemctl daemon-reload # 5. 启动服务 sudo systemctl start rust-api # 6. 设置开机自启 sudo systemctl enable rust-api # 7. 查看状态 sudo systemctl status rust-api # 8. 查看日志 sudo journalctl -u rust-api -f ``` #### Windows 服务 使用 NSSM (Non-Sucking Service Manager) 将应用注册为 Windows 服务: ```powershell # 1. 下载 NSSM # 访问 https://nssm.cc/download # 2. 解压并添加到 PATH # 3. 安装服务 nssm install RustApiService "C:\path\to\api-host.exe" # 4. 配置服务 nssm set RustApiService AppDirectory "C:\path\to\app" nssm set RustApiService AppParameters "" nssm set RustApiService AppEnvironmentExtra "RUST_LOG=info" "CONFIG_PATH=C:\path\to\config\production.toml" nssm set RustApiService DisplayName "Rust API Service" nssm set RustApiService Description "Rust通用系统后端API服务" nssm set RustApiService Start SERVICE_AUTO_START # 5. 启动服务 nssm start RustApiService # 6. 停止服务 nssm stop RustApiService # 7. 删除服务 nssm remove RustApiService confirm ``` #### 使用 Nginx 反向代理 创建 Nginx 配置 `/etc/nginx/sites-available/rust-api`: ```nginx upstream rust_api { least_conn; server 127.0.0.1:8080 max_fails=3 fail_timeout=30s; # 如果有多个实例,可以添加更多服务器 # server 127.0.0.1:8081 max_fails=3 fail_timeout=30s; } server { listen 80; server_name api.example.com; # 重定向到 HTTPS return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name api.example.com; # SSL 证书配置 ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; # 日志 access_log /var/log/nginx/rust-api-access.log; error_log /var/log/nginx/rust-api-error.log; # 客户端请求体大小限制 client_max_body_size 10M; # 超时设置 proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; # 代理设置 location / { proxy_pass http://rust_api; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # WebSocket 支持(如果需要) proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } # API 代理(可根据需要添加健康检查端点) } ``` 启用配置: ```bash sudo ln -s /etc/nginx/sites-available/rust-api /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx ``` ### 配置管理 #### 环境变量配置 应用支持通过环境变量覆盖配置: ```bash # 数据库配置 export DATABASE__MASTER_URL="postgresql://user:pass@host:5432/db" export DATABASE__MAX_CONNECTIONS=100 # Redis 配置 export REDIS__URL="redis://host:6379" export REDIS__MAX_CONNECTIONS=50 # 服务器配置 export SERVER__HOST="0.0.0.0" export SERVER__PORT=8080 # 日志配置 export LOGGING__LEVEL="info" export LOGGING__FORMAT="json" ``` #### 多环境配置 创建不同环境的配置文件: ```bash api-host/config/ ├── development.toml # 开发环境 ├── staging.toml # 预发布环境 └── production.toml # 生产环境 ``` 通过环境变量选择配置: ```bash export CONFIG_ENV=production # 或 development, staging ``` ### 监控和日志 #### 日志管理 应用使用 `tracing` 进行结构化日志记录: ```bash # 查看实时日志(systemd) sudo journalctl -u rust-api -f # 查看最近的日志 sudo journalctl -u rust-api -n 100 # 按时间范围查看 sudo journalctl -u rust-api --since "2024-01-01" --until "2024-01-02" # 查看错误日志 sudo journalctl -u rust-api -p err ``` #### 健康检查 如需健康检查功能,可以: 1. 在路由中添加健康检查端点 2. 或使用 Nginx 直接检查 HTTP 响应状态码 #### 性能监控 建议使用以下工具进行监控: 1. **Prometheus + Grafana** - 指标收集和可视化 - 需要添加 metrics 端点 2. **ELK Stack (Elasticsearch, Logstash, Kibana)** - 日志聚合和分析 3. **Sentry** - 错误追踪和监控 ### 性能优化建议 #### 1. 应用层优化 - **连接池配置**:根据实际负载调整数据库和 Redis 连接池大小 - **工作线程数**:设置为 CPU 核心数 - **缓存策略**:合理使用多级缓存,设置合适的 TTL #### 2. 系统层优化 ```bash # 增加文件描述符限制 echo "* soft nofile 65536" | sudo tee -a /etc/security/limits.conf echo "* hard nofile 65536" | sudo tee -a /etc/security/limits.conf # 调整 TCP 参数 sudo sysctl -w net.core.somaxconn=1024 sudo sysctl -w net.ipv4.tcp_max_syn_backlog=2048 sudo sysctl -w net.ipv4.ip_local_port_range="10000 65535" ``` #### 3. 数据库优化 - 创建适当的索引 - 使用连接池 - 定期执行 `VACUUM ANALYZE` - 监控慢查询 #### 4. Redis 优化 - 配置持久化策略(AOF 或 RDB) - 设置合理的内存限制 - 使用 Redis Cluster 进行高可用 ### 备份和恢复 #### 数据库备份 ```bash # PostgreSQL 备份 pg_dump -h localhost -U postgres -d rust_api > backup_$(date +%Y%m%d).sql # 恢复 psql -h localhost -U postgres -d rust_api < backup_20240101.sql ``` #### Redis 备份 ```bash # Redis 备份(如果启用了 RDB) cp /var/lib/redis/dump.rdb backup_$(date +%Y%m%d).rdb # 或使用 Redis 命令 redis-cli BGSAVE ``` ### 故障排查 #### 常见问题 1. **服务无法启动** ```bash # 检查日志 sudo journalctl -u rust-api -n 50 # 检查端口占用 sudo netstat -tlnp | grep 8080 # 检查配置文件 ./api-host --check-config ``` 2. **数据库连接失败** ```bash # 测试数据库连接 psql -h localhost -U postgres -d rust_api # 检查连接池配置 # 查看应用日志中的连接错误 ``` 3. **Redis 连接失败** ```bash # 测试 Redis 连接 redis-cli ping # 检查 Redis 配置 redis-cli CONFIG GET "*" ``` 4. **性能问题** ```bash # 查看系统资源 htop # 查看应用指标 curl http://localhost:8080/metrics # 如果实现了 metrics 端点 # 分析慢查询(PostgreSQL) # 启用 log_min_duration_statement ``` ## 性能优化 - 使用多级缓存(本地缓存 + Redis) - 数据库读写分离 - 异步I/O操作 - 零拷贝技术 ## 依赖说明 ### 系统级依赖 本项目使用了以下需要系统级依赖的库: | 依赖库 | 系统工具需求 | 说明 | |--------|------------|------| | `reqwest` (native-tls) | CMake, C++ 编译器 | HTTP 客户端,默认使用 native-tls | | `diesel` + Postgres | PostgreSQL 服务与客户端库 | 数据库 ORM / 查询构建器 | | `aws-lc-sys` | CMake | TLS 库的底层实现 | ### 避免系统依赖的方案 如果不想安装系统构建工具,可以使用纯 Rust 实现的替代方案: 1. **使用 rustls 替代 native-tls** - 修改 `Cargo.toml` 中的特性配置(见上方"替代方案") - 优点:无需系统构建工具,纯 Rust 实现 - 缺点:可能在某些场景下性能略低于 native-tls 2. **使用预编译的二进制** - 使用 Docker 容器构建 - 使用 CI/CD 预编译的二进制文件 ### 数据库迁移工具 建议使用 Diesel 的迁移工具 `diesel_cli`: ```bash cargo install diesel_cli --no-default-features --features postgres ``` ## 完整的系统依赖清单 ### Windows | 工具 | 用途 | 安装方法 | |------|------|---------| | CMake | 构建 aws-lc-sys | `winget install Kitware.CMake` | | Visual Studio Build Tools | C++ 编译器 | `winget install Microsoft.VisualStudio.2022.BuildTools` | | PostgreSQL | 数据库服务器 | `winget install PostgreSQL.PostgreSQL` | | Redis | 缓存服务器 | `winget install Redis.Redis` | > **注意**:如果遇到 Perl 相关错误(见下方"常见构建问题"),需要安装 **Strawberry Perl**:`winget install StrawberryPerl.StrawberryPerl` ### Linux (Ubuntu/Debian) ```bash sudo apt-get update sudo apt-get install -y \ build-essential \ cmake \ pkg-config \ libssl-dev \ libpq-dev \ postgresql-server-dev-all \ redis-server ``` ### Linux (Fedora) ```bash sudo dnf install \ gcc \ gcc-c++ \ cmake \ pkg-config \ openssl-devel \ postgresql-devel \ postgresql-server \ redis ``` ### macOS ```bash # 安装 Xcode Command Line Tools xcode-select --install # 使用 Homebrew 安装 brew install cmake openssl pkg-config postgresql redis ``` ## 许可证 MIT