-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionPool.cpp
More file actions
80 lines (63 loc) · 1.8 KB
/
Copy pathConnectionPool.cpp
File metadata and controls
80 lines (63 loc) · 1.8 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
#include "ConnectionPool.h"
#include "MutexLockGuard.h"
#include "Logger.h"
#include <iostream>
using namespace std;
ConnectionPool::~ConnectionPool() {
destoryPool();
}
void ConnectionPool::init(string url, string userName, string passWd,
string databaseName, int port, int maxConnNum) {
url_ = url;
userName_ = userName;
passWd_ = passWd;
databaseName_ = databaseName;
port_ = port;
maxConnNum_ = maxConnNum;
for (int i = 0; i < maxConnNum; i++) {
MYSQL* con = NULL;
con = mysql_init(con);
if (con == NULL) {
LOG_ERROR("mysql_init error!");
}
con = mysql_real_connect(con, url_.c_str(), userName_.c_str(), passWd_.c_str(),
databaseName_.c_str(), port_, NULL, 0);
if (con == NULL) {
LOG_ERROR("mysql_real_connect error!");
}
conns_.push_back(con);
}
}
ConnectionPool* ConnectionPool::getInstance() {
static ConnectionPool connPool;
return &connPool;
}
MYSQL* ConnectionPool::getConn() {
// 可能被多个线程访问,需要保证线程安全
MutexLockGuard guard(mtx_);
while (conns_.empty()) {
cond_.wait(mtx_);
}
MYSQL* con;
con = conns_[conns_.size()-1];
conns_.pop_back();
return con;
}
void ConnectionPool::releaseConn(MYSQL* conn) {
MutexLockGuard guard(mtx_);
conns_.push_back(conn);
cond_.signal();
}
void ConnectionPool::destoryPool() {
for (int i = 0; i < conns_.size(); i++) {
mysql_close(conns_[i]);
}
}
ConnectionPoolRAII::ConnectionPoolRAII(MYSQL** mysql, ConnectionPool* connPool) {
*mysql = connPool->getConn();
mysql_ = *mysql;
connPool_ = connPool;
}
ConnectionPoolRAII::~ConnectionPoolRAII() {
connPool_->releaseConn(mysql_);
}