1use std::collections::VecDeque;
2use std::sync::Mutex;
3use crate::config::Config;
4use crate::connect::Connect;
5
6pub(crate) static DB_POOL: std::sync::LazyLock<Mutex<VecDeque<Connect>>> = std::sync::LazyLock::new(|| Mutex::new(VecDeque::new()));
7
8#[derive(Clone)]
9pub struct Pools {
10 pub config: Config,
12 max_pools: usize,
14}
15
16impl Pools {
17 pub fn new(config: Config, size: usize) -> Result<Self, String> {
19 for _ in 0..size {
20 let client = Connect::new(config.clone())?;
21 DB_POOL.lock().unwrap().push_back(client);
22 }
23 Ok(Self { config, max_pools: size })
24 }
25
26 pub fn get_connect(&mut self) -> Result<Connect, String> {
28 loop {
29 let mut pool = DB_POOL.lock().unwrap();
30 if pool.is_empty() {
32 } else if pool.len() <= self.max_pools {
34 return Ok(pool.pop_front().unwrap());
35 }
36 }
37
38 }
58
59 pub fn _release_conn(&self, conn: Connect) {
61 if conn.is_valid() {
62 let mut pool = DB_POOL.lock().unwrap();
63 pool.push_back(conn); } else {
65 }
67 }
68
69 pub fn current_pool_size(&self) -> usize {
71 let pool = DB_POOL.lock().unwrap();
72 pool.len()
73 }
74
75 pub fn _cleanup_idle_connections(&self) {
77 let mut pool = DB_POOL.lock().unwrap();
78 println!("当前连接池中的连接数量(清理前): {}", pool.len());
79
80 pool.retain(|conn| {
81 let is_ok = conn.stream.peer_addr().is_ok();
82 if !is_ok {
83 println!("检测到无效连接,已移除");
84 }
85 is_ok
86 });
87
88 println!("当前连接池中的连接数量(清理后): {}", pool.len());
89 }
90}