-
Notifications
You must be signed in to change notification settings - Fork 1
/
uconnectionpool.cpp
69 lines (59 loc) · 1.64 KB
/
uconnectionpool.cpp
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
#include <QUuid>
#include <QMutex>
#include <QDebug>
#include <QHostInfo>
#include <QSqlError>
#include <QMutexLocker>
#include "uutil.h"
#include "uconfig.h"
#include "urequest.h"
#include "uconnectionpool.h"
uConnectionPool::uConnectionPool(QObject *parent) :
QObject(parent),
m_counter(0), m_config(0)
{
m_config = &uConfig::getInstance();
createPool(PoolSize);
}
uConnectionPool::~uConnectionPool()
{
foreach (QString name, m_pool)
{
QSqlDatabase::removeDatabase(name);
}
}
void uConnectionPool::createPool(int size)
{
for (int i = 0; i < size; i++)
{
m_pool.append(createConnection());
}
}
QString uConnectionPool::createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase(m_config->value("database/driver", "QMYSQL").toString(), uUtil::uuid());
db.setDatabaseName(m_config->value("database/name", "").toString());
db.setHostName(m_config->value("database/hostname", "localhost").toString());
db.setUserName(m_config->value("database/username", "").toString());
db.setPassword(m_config->value("database/password", "").toString());
return db.connectionName();
}
bool uConnectionPool::connection(QSqlDatabase &con)
{
static QMutex mutex;
QMutexLocker lock(&mutex);
Q_UNUSED(lock);
int index = (m_counter % PoolSize);
con = QSqlDatabase::database(m_pool.at(index), true);
m_counter++;
if (m_counter >= 1000) m_counter = 0;
return (con.isOpen() || con.open());
}
uConnectionPool &uConnectionPool::getInstance()
{
static QMutex mutex;
QMutexLocker lock(&mutex);
Q_UNUSED(lock);
static uConnectionPool instance;
return instance;
}