spring-postgres插件
spring-postgres是针对rust-postgres的自动装配
tokio-postgres是和sqlx类似的数据库连接工具,和sqlx不同的是它只专注于实现postgresql的数据库连接。
依赖
spring-postgres = { version = "<version>" }
可选的features:
array-implsjswith-bit-vec-0_6with-chrono-0_4with-eui48-0_4with-eui48-1with-geo-types-0_6with-geo-types-0_7with-serde_json-1with-smol_str-01with-time-0_2with-time-0_3with-uuid-0_8with-uuid-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