-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmySQLConnectionPool.cpp
More file actions
92 lines (80 loc) · 2.23 KB
/
mySQLConnectionPool.cpp
File metadata and controls
92 lines (80 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "mySQLConnectionPool.h"
MySQLConnectionPool::MySQLConnectionPool(const string& host,
const string& user,
const string& password,
const string& database,
int poolSize,
int heartbeatInterval)
: host_(host),
user_(user),
password_(password),
database_(database),
poolSize_(poolSize),
heartbeatInterval_(heartbeatInterval) {
driver_ = mysql::get_mysql_driver_instance();
initializePool();
startHeartbeat();
}
MySQLConnectionPool::~MySQLConnectionPool() {
stopHeartbeat();
for (auto& conn : connectionPool_) {
delete conn;
}
}
Connection* MySQLConnectionPool::getConnection() {
unique_lock<mutex> lock(mutex_);
while (connectionPool_.empty()) {
condition_.wait(lock);
}
Connection* conn = connectionPool_.back();
connectionPool_.pop_back();
// Check connection validity
if (!conn->isValid()) {
delete conn;
conn = driver_->connect(host_, user_, password_);
conn->setSchema(database_);
connectionPool_.push_back(conn);
}
return conn;
}
void MySQLConnectionPool::releaseConnection(Connection* conn) {
unique_lock<mutex> lock(mutex_);
connectionPool_.push_back(conn);
condition_.notify_one();
}
void MySQLConnectionPool::initializePool() {
for (int i = 0; i < poolSize_; ++i) {
Connection* conn = driver_->connect(host_, user_, password_);
conn->setSchema(database_);
connectionPool_.push_back(conn);
}
cout << "Initialize Pool" << endl;
}
void MySQLConnectionPool::startHeartbeat() {
heartbeatThread_ = thread([this]() {
while (heartbeatRunning_) {
this_thread::sleep_for(chrono::seconds(heartbeatInterval_));
checkConnections();
}
});
cout << "Started Heartbeat" << endl;
}
void MySQLConnectionPool::stopHeartbeat() {
if (heartbeatThread_.joinable()) {
heartbeatRunning_ = false;
heartbeatThread_.join();
}
}
void MySQLConnectionPool::checkConnections() {
lock_guard<mutex> lock(mutex_);
for (auto& conn : connectionPool_) {
if (!conn->isValid()) {
delete conn;
conn = driver_->connect(host_, user_, password_);
conn->setSchema(database_);
cout << "Reconnected Connection" << endl;
}
cout << "Checked Connection" << endl;
}
cout << "Checked all Connections" << endl;
}