Hero Background

Rust 学习笔记:Axum 与 GraphQL

更新于 2026-05-13
技术

为什么选 Rust + Axum

最近用 Rust 写了一个个人站点的后端,记录一下技术选型的心得。

Axum

Axum 是 Tokio 团队开发的 Web 框架,设计简洁,与 tower 生态完美集成。

Rust
use axum::{Router, routing::get, extract::State};

#[derive(Clone)]
struct AppState {
    db: PgPool,
}

async fn handler(State(state): State<AppState>) -> String {
    format!("连接池大小: {}", state.db.size())
}

#[tokio::main]
async fn main() {
    let state = AppState { /* ... */ };
    let app = Router::new()
        .route("/api/health", get(handler))
        .with_state(state);
}

async-graphql

配合 async-graphql 可以非常方便地搭建 GraphQL API:

Rust
#[Object]
impl QueryRoot {
    async fn posts(&self, ctx: &Context<'_>) -> Result<Vec<PostType>> {
        let pool = ctx.data::<PgPool>()?;
        let posts = sqlx::query_as::<_, Post>("SELECT * FROM posts")
            .fetch_all(pool)
            .await?;
        Ok(posts.into_iter().map(Into::into).collect())
    }
}

环境变量配置

[!WARNING] 不要将 .env 文件提交到 Git!

Shell
# .env 示例
POSTGRES_URL_NON_POOLING=postgres://user:pass@host:5432/db
SUPABASE_URL=https://your-project.supabase.co

连接池的那些坑

关于连接池的配置,之前踩过一个坑:

配置
之前
之后
min_connections
1
0
idle_timeout
60s
max_lifetime
300s

在 Serverless 环境下,连接池需要用点心 需要合理配置超时参数。


完整代码可以看这里喵~ 🦀

©2026 fufu all|