1#ifndef NEFORCE_DATABASE_DATABASE_POOL_HPP__
2#define NEFORCE_DATABASE_DATABASE_POOL_HPP__
18NEFORCE_BEGIN_NAMESPACE__
57 struct connection_entry {
61 connection_entry() noexcept = default;
63 explicit connection_entry(idb_connect* c) :
65 idle_at(current_ms()) {}
67 milliseconds idle_duration() const noexcept {
return current_ms() - idle_at; }
73 pool_config pool_cfg_;
74 unique_ptr<idb_factory> factory_;
76 queue<connection_entry> idle_queue_;
77 mutable mutex queue_mtx_;
78 condition_variable cv_;
80 atomic<size_t> total_count_{0};
81 atomic<bool> running_{
false};
83 thread replenish_thread_;
84 thread scanner_thread_;
86 idb_connect* try_create_connect() noexcept;
88 void return_connect(idb_connect* conn);
90 void replenish_task();
94 shared_ptr<T> acquire_impl();
182 [
this] { return !idle_queue_.empty() || !running_.load(memory_order_relaxed); });
188 if (!got || idle_queue_.empty()) {
190 if (cur >= pool_cfg_.max_size) {
193 idb_connect* raw = try_create_connect();
194 if (raw ==
nullptr) {
199 T* typed =
dynamic_cast<T*
>(raw);
200 if (typed ==
nullptr) {
205 return shared_ptr<T>(typed, [
this](T* p) { this->return_connect(p); });
208 const connection_entry entry = idle_queue_.front();
212 idb_connect* raw = entry.conn;
223 T* typed =
dynamic_cast<T*
>(raw);
224 if (typed ==
nullptr) {
225 this->return_connect(raw);
229 return shared_ptr<T>(typed, [
this](T* p) { this->return_connect(p); });
235NEFORCE_END_NAMESPACE__
cv_status wait_for(unique_lock< mutex > &lock, const duration< Rep, Period > &rest)
等待指定的持续时间
database_pool(db_type type, const db_config &config)
构造函数
size_t idle_count() const noexcept
获取空闲连接数
size_t total_count() const noexcept
获取总连接数
shared_ptr< idb_tb_connect > get_tb_connect()
获取关系型数据库连接
shared_ptr< idb_connect > get_connect()
获取通用数据库连接
shared_ptr< idb_kv_connect > get_kv_connect()
获取键值存储连接
bool is_running() const noexcept
检查连接池是否正在运行
database_pool(db_type type, const db_config &config, const pool_config &pool_config)
构造函数
duration< int64_t, milli > milliseconds
毫秒持续时间
constexpr ToDur time_cast(const duration< Rep, Period > &value)
持续时间类型转换
duration< int64_t > seconds
秒持续时间
NEFORCE_INLINE17 constexpr auto memory_order_relaxed
宽松内存顺序常量
NEFORCE_INLINE17 constexpr auto memory_order_acquire
获取内存顺序常量
bool load(const memory_order mo=memory_order_seq_cst) const noexcept
原子加载操作
seconds max_idle_time
连接最大空闲时间
milliseconds acquire_timeout
获取连接超时时间
virtual bool reconnect(const db_config &config)=0
重新连接
virtual bool is_valid() const =0
检查连接有效性
static time_point now() noexcept
获取当前时间点