pub struct DbPool { /* private fields */ }Expand description
连接池管理器
Implementations§
Source§impl DbPool
impl DbPool
Sourcepub async fn with_config(config: DbConfig) -> DbResult<Self>
pub async fn with_config(config: DbConfig) -> DbResult<Self>
使用配置创建连接池
Sourcepub async fn try_from_config(config: DbConfig) -> DbResult<Self>
pub async fn try_from_config(config: DbConfig) -> DbResult<Self>
使用配置结构体创建连接池
此方法接受一个 DbConfig 结构体,用于配置连接池的所有参数。
与 Self::new 方法功能相同,但更适合从配置结构体直接初始化。
§Example
/// ```rust
/// use dbnexus::DbPool;
/// use dbnexus::config::DbConfig;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = DbConfig {
/// url: "sqlite::memory:".to_string(),
/// max_connections: 10,
/// min_connections: 2,
/// ..Default::default()
/// };
///
/// let pool = DbPool::try_from_config(config).await?;
/// Ok(())
/// }
/// ```§Errors
如果连接失败或配置无效,返回错误
Sourcepub fn try_from(config: &DbConfig) -> Result<Self, ConfigError>
pub fn try_from(config: &DbConfig) -> Result<Self, ConfigError>
使用配置引用同步创建连接池(简化版本,带权限但不初始化缓存)
此方法是同步的,不会创建数据库连接。 实际的连接池创建和连接验证在首次获取连接时进行。
注意:此方法不会初始化权限缓存(需要异步初始化)。
如果需要完整的异步权限缓存功能,请使用 with_config() 异步方法。
§Example
ⓘ
use dbnexus::DbPool;
use dbnexus::config::DbConfig;
let runtime = tokio::runtime::Runtime::new()?;
let _guard = runtime.enter();
let config = DbConfig {
url: "sqlite::memory:".to_string(),
max_connections: 10,
min_connections: 1,
idle_timeout: 300,
acquire_timeout: 5000,
..Default::default()
};
let pool = DbPool::try_from(&config)?;§Errors
如果配置验证失败,返回错误
Sourcepub fn metrics(&self) -> Option<&Arc<MetricsCollector>>
pub fn metrics(&self) -> Option<&Arc<MetricsCollector>>
获取指标收集器(如果已设置)
Sourcepub fn get_actual_config(&self) -> &DbConfig
pub fn get_actual_config(&self) -> &DbConfig
Sourcepub async fn get_session(&self, role: &str) -> DbResult<Session>
pub async fn get_session(&self, role: &str) -> DbResult<Session>
从池中获取 Session(带 metrics 支持)
§Arguments
role- 角色名称,必须在权限配置中定义
§Errors
如果角色未在权限配置中定义,返回错误
§安全警告
此方法接受角色字符串参数,调用者应确保:
- 已通过其他方式验证用户身份(如JWT Token、API Key等)
- 角色字符串来自可信来源,而非直接的用户输入
- 在生产环境中不要硬编码角色字符串
- 建议结合
dbnexus::authentication::AuthenticationManager使用
§示例
ⓘ
use dbnexus::{DbPool, authentication::AuthenticationManager};
// 安全用法:先验证Token,再从Token中提取角色
let auth_manager = AuthenticationManager::new(&jwt_secret);
let claims = auth_manager.verify_token(token)?;
let session = pool.get_session(&claims.role).await?;
// 不安全用法:直接使用用户输入
// let session = pool.get_session(user_input_role).await?; // 不要这样做!Sourcepub async fn check_connection_health(&self, conn: &DbConnection) -> bool
pub async fn check_connection_health(&self, conn: &DbConnection) -> bool
Sourcepub async fn clean_invalid_connections(&self) -> u32
pub async fn clean_invalid_connections(&self) -> u32
Sourcepub async fn validate_and_recreate_connections(&self) -> Result<u32, DbErr>
pub async fn validate_and_recreate_connections(&self) -> Result<u32, DbErr>
Sourcepub fn parse_health_check_interval(value: &str) -> u64
pub fn parse_health_check_interval(value: &str) -> u64
解析健康检查间隔配置
解析传入的间隔值(秒),并限制在 5-300 秒范围内。 超出范围的值会触发警告日志。
§Arguments
value- 健康检查间隔配置值(由调用方从环境变量DB_HEALTH_CHECK_INTERVAL读取)
§Returns
返回解析后的间隔秒数,默认为 30 秒。
§Examples
use dbnexus::DbPool;
// 空字符串返回默认值 30
assert_eq!(DbPool::parse_health_check_interval(""), 30);
// 有效值返回该值
assert_eq!(DbPool::parse_health_check_interval("60"), 60);
// 超出范围的值返回限制后的值
assert_eq!(DbPool::parse_health_check_interval("1000"), 300);Sourcepub fn status(&self) -> PoolStatus
pub fn status(&self) -> PoolStatus
Sourcepub fn pool_metrics(&self) -> PoolMetrics
pub fn pool_metrics(&self) -> PoolMetrics
获取连接池告警指标
从 metrics_collector(如果启用)获取告警相关指标,包括:
slow_acquires:获取时长超过 1s 的次数timeout_errors:获取超时总次数(warn + error + critical 之和)critical_timeouts:严重超时(≥10s)次数wait_count:当前正在等待获取连接的协程数max_waiters:历史最大并发等待者峰值
§Returns
连接池告警指标(始终返回有效值,metrics 未启用时所有计数为 0)
Sourcepub async fn run_auto_migrate(&self) -> Result<u32, DbError>
pub async fn run_auto_migrate(&self) -> Result<u32, DbError>
Trait Implementations§
Source§impl ConnectionPool for DbPool
impl ConnectionPool for DbPool
Auto Trait Implementations§
impl !RefUnwindSafe for DbPool
impl !UnwindSafe for DbPool
impl Freeze for DbPool
impl Send for DbPool
impl Sync for DbPool
impl Unpin for DbPool
impl UnsafeUnpin for DbPool
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self>
fn with_context(self, otel_cx: Context) -> WithContext<Self>
Source§fn with_current_context(self) -> WithContext<Self>
fn with_current_context(self) -> WithContext<Self>
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
Converts
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
Converts
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
Wrap the input message
T in a tonic::Request