Skip to main content

Pool

Struct Pool 

Source
pub struct Pool { /* private fields */ }
Expand description

连接池核心实现

所有字段均为 Arc 或内部含 ArcNotifyPoolConfig 可 clone), 因此 Pool 可低成本 clone(仅增加引用计数)。PooledConnection 持有 Pool 的 clone 以实现 Drop 自动归还。

Implementations§

Source§

impl Pool

Source

pub fn new( config: PoolConfig, factory: Arc<dyn ConnectionFactory>, ) -> Result<Pool, PoolError>

创建连接池

L-5 修复:补充示例文档

§示例
use sz_orm_pool::pool::{Pool, PoolConfig, PoolConfigBuilder, ConnectionFactory};
use std::sync::Arc;

struct MyFactory;
impl ConnectionFactory for MyFactory {
    // ...
}

let config = PoolConfigBuilder::new()
    .max_size(10)
    .acquire_timeout(std::time::Duration::from_secs(30))
    .build();
let pool = Pool::new(config, Arc::new(MyFactory))?;
Source

pub fn config(&self) -> &PoolConfig

获取配置

Source

pub fn configure_circuit_breaker( &self, failure_threshold: usize, reset_timeout: Duration, )

#88 修复:配置断路器(启用 circuit-breaker feature 时生效)

替换默认的断路器实例。调用此方法可自定义 failure_thresholdreset_timeout

§示例
pool.configure_circuit_breaker(10, Duration::from_secs(60));
Source

pub fn reset_circuit_breaker(&self) -> bool

#88 修复:手动重置断路器到 Closed 状态

用于故障排除后手动恢复,无视当前 reset_timeout 是否到达。 返回是否实际发生了状态变更。

Source

pub fn circuit_state(&self) -> CircuitState

#88 修复:获取断路器当前状态

Source

pub async fn acquire(&self) -> Result<PooledConnection, PoolError>

从池中获取连接(带超时)

L-5 修复:补充示例文档

超时时间由 PoolConfig::acquire_timeout 控制,默认 30 秒。 若超时则返回 PoolError::AcquireTimeout

§示例
// 从池中获取连接
let conn = pool.acquire().await?;
// 使用连接执行查询...
// conn.query("SELECT 1").await?;
Source

pub async fn release(&self, pooled: PooledConnection)

释放连接回池中 如果池已关闭或连接已断开,则直接关闭连接而不是放回池中。

接收 PooledConnection 以保留原始 created_at,避免 max_lifetime 在每次归还后被重置(Critical bug fix)。

显式调用 release 后,pooled.pool 设为 None,避免 Drop 重复归还。

Source

pub async fn status(&self) -> PoolStatus

获取池状态

v1.1.0 优化 2:idle 长度从 Mutex::lock().await 改为 ArrayQueue::len() (原子 load,无任何等待)。该方法保留 async 签名以兼容旧调用方。

Source

pub async fn reap_idle(&self)

回收空闲过久的连接

Source

pub async fn close_all(&self)

关闭所有空闲连接,并标记池为已关闭 注意:已借出未归还的连接不受影响,但归还时会被直接关闭; 同时 close_all 后的新 acquire 也会被拒绝。

Source

pub async fn health_check(&self) -> u32

M-7 修复:连接池健康检查(heartbeat)

对所有空闲连接执行 ping(),移除已断开或 ping 失败的连接。 调用方应定期调用此方法(如每 60 秒),以清理失效连接。

§返回值

返回被移除的连接数。

§注意
  • v1.1.0 优化 2 后:使用无锁 ArrayQueue,不再持 Mutex 锁。 仍可能在 ping 期间阻塞 acquire(因为连接已被取出),但不再阻塞 release。
  • 仅检查空闲连接,不影响已借出的连接
  • 对于大量空闲连接,可能产生较多并发 ping,建议在低峰期执行
Source

pub async fn shutdown(&self)

优雅停机:关闭所有空闲连接,等待所有在途连接归还

  1. 标记池为已关闭(拒绝新 acquire)
  2. 通知所有等待者(让 acquire 等待者立即返回 Closed 错误)
  3. 关闭所有空闲连接(立即释放,避免 wait 阶段无意义等待)
  4. 等待在途(已借出)连接归还(带 30 秒超时)
Source

pub fn resize(&self, new_max: usize)

动态调整连接池最大容量(resize 的别名,接受 usize)

简化实现:仅更新动态 max_size 值,在 acquire 时检查新值。

  • 如果 new_max 大于当前值,允许创建更多连接(受 ArrayQueue 容量限制: 超出原始 max_size 的空闲连接会在 release 时因队列满而被关闭)
  • 如果 new_max 小于当前值,不立即关闭多余连接,但阻止新连接创建 (多余连接会在 release/reap_idle 时自然回收)
Source

pub fn set_max_size(&self, new_max: u32)

动态调整连接池最大容量

Source

pub fn max_size(&self) -> u32

获取当前动态 max_size

Source

pub async fn warmup(&self, min_idle: usize) -> Result<(), PoolError>

预热连接池:创建指定数量的连接放入空闲队列

不会超过 dynamic_max_size 上限。创建失败时停止预热并返回 Ok。

Source

pub async fn query_with_timeout( &self, sql: &str, ) -> Result<Vec<HashMap<String, Value>>, DbError>

带超时的查询执行

强制 query_timeout 配置生效:使用 tokio::time::timeout 包裹 conn.query(sql),超时返回 DbError::QueryError。未配置时使用 30 秒默认值。

Trait Implementations§

Source§

impl Clone for Pool

Pool 克隆:仅增加 Arc 引用计数,成本极低

克隆后的 Pool 与原 Pool 共享同一组连接池状态(idle 队列、计数器等)。

Source§

fn clone(&self) -> Pool

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Pool

§

impl !UnwindSafe for Pool

§

impl Freeze for Pool

§

impl Send for Pool

§

impl Sync for Pool

§

impl Unpin for Pool

§

impl UnsafeUnpin for Pool

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

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 more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more