spring-sqlx插件
spring-sqlx是针对sqlx的自动装配
依赖
spring-sqlx = { version = "<version>", features = ["mysql"] }
可以替换postgres、mysql、sqlitefeature来选择合适的数据库驱动。
可选的features:
with-jsonwith-chronowith-rust_decimalwith-bigdecimalwith-uuidwith-time
配置项
[sqlx]
uri = "postgres://root:123456@localhost:5432/pg_db"  # 数据库地址
min_connections = 1                                  # 连接池的最小连接数,默认值为1
max_connections = 10                                 # 连接池的最大连接数,默认值为10
acquire_timeout = 30000                              # 占用连接超时时间,单位毫秒,默认30s
idle_timeout = 600000                                # 连接空闲时间,单位毫秒,默认10min
connect_timeout = 1800000                            # 连接的最大存活时间,单位毫秒,默认30min
组件
配置完上述配置项后,插件会自动注册一个ConnectPool连接池对象。该对象是sqlx::AnyPool的别名。
pub type ConnectPool = sqlx::AnyPool;
提取插件注册的Component
SqlxPlugin插件为我们自动注册了一个Sqlx连接池组件,我们可以使用Component从AppState中提取这个连接池,Component是一个axum的extractor。
use spring_sqlx::{sqlx::{self, Row}, ConnectPool};
use spring_web::get;
use spring_web::extractor::Component;
use spring_web::error::Result;
use anyhow::Context;
#[get("/version")]
async fn mysql_version(Component(pool): Component<ConnectPool>) -> Result<String> {
    let version = sqlx::query("select version() as version")
        .fetch_one(&pool)
        .await
        .context("sqlx query failed")?
        .get("version");
    Ok(version)
}
完整代码参考sqlx-example