spring-postgres插件

spring-postgres是针对rust-postgres的自动装配

crates.io Documentation

tokio-postgres是和sqlx类似的数据库连接工具,和sqlx不同的是它只专注于实现postgresql的数据库连接。

依赖

spring-postgres = { version = "0.1.1" }

配置项

[postgres]
connect = "postgres://root:12341234@localhost:5432/myapp_development"  # 要连接的数据库地址

组件

配置完上述配置项后,插件会自动注册一个Postgres对象。该对象包装了tokio_postgres::Client

pub struct Postgres(Arc<tokio_postgres::Client>);

提取插件注册的Component

PgPlugin插件为我们自动注册了一个Postgres对象,我们可以使用Component从AppState中提取这个连接池,Component是一个axum的extractor

#[get("/postgres")]
async fn hello_postgres(Component(pg): Component<Postgres>) -> Result<impl IntoResponse> {
    let rows = pg
        .query("select version() as version", &[])
        .await
        .context("query postgresql failed")?;

    let version: String = rows[0].get("version");

    Ok(Json(version))
}

完整代码参考postgres-example