头文件:
#pragma once
#include <string>
#include <list>
#include <thread>
#include <mutex>
#include <cppconn\driver.h>
#include <cppconn\exception.h>
#include <cppconn\resultset.h>
#include <cppconn\statement.h>
#include <cppconn\sqlstring.h>
using namespace std;
using namespace sql;
class MysqlConnPool
{
public:
~MysqlConnPool();
shared_ptr<Connection> getConn();
void releaseConn(shared_ptr<Connection> conn);
static MysqlConnPool *ins();
private:
shared_ptr<Connection> createConnection(); //创建一个连接
void initConnPool();
MysqlConnPool(const char *url, const char *user, const char *password, int maxSize); //构造方法
list<shared_ptr<Connection>> connList;
mutex lock; //线程锁
static MysqlConnPool *connPool;
Driver *driver;
SQLString url;
SQLString user;
SQLString pwd;
int poolSize;
};
源文件:
#include "stdafx.h"
#include "MysqlConnPool.h"
MysqlConnPool *MysqlConnPool::connPool =
new MysqlConnPool("tcp://192.168.1.99:3306", "chuer", "123456", 10);
MysqlConnPool::MysqlConnPool(const char * url, const char * user, const char * password, int maxSize)
{
this->url = url;
this->user = user;
this->pwd = password;
this->poolSize = maxSize;
this->driver = get_driver_instance();
initConnPool();
}
void MysqlConnPool::initConnPool() {
for (int i = 0; i < this->poolSize; ++i) {
connList.push_back(createConnection());
}
}
shared_ptr<Connection> MysqlConnPool::createConnection() {
//建立连接
try {
Connection *conn = driver->connect(this->url, this->user, this->pwd);
shared_ptr<Connection> conSpt(conn);
return conSpt;
} catch (exception &e) {
cout << "createConnection error:" << e.what() << endl;
}
}
MysqlConnPool *MysqlConnPool::ins()
{
return connPool;
}
shared_ptr<Connection> MysqlConnPool::getConn() {
cout << "pool size:" << connList.size() << endl;
lock.lock();
if (connList.size() > 0){
shared_ptr<Connection> conn = connList.front();
connList.pop_front();
if (conn->isClosed()) {
conn.reset();
return createConnection();
}
lock.unlock();
return conn;
} else {
lock.unlock();
return createConnection();
}
}
void MysqlConnPool::releaseConn(shared_ptr<Connection> conn) {
if (conn->isClosed()) {
conn.reset();
lock.lock();
connList.push_back(createConnection());
lock.unlock();
} else {
connList.push_back(conn);
}
}
MysqlConnPool::~MysqlConnPool()
{
while (connList.size() > 0) {
shared_ptr<Connection> con = connList.front();
con.reset();
connList.pop_front();
}
delete connPool;
}
void testConn(){
MysqlConnPool *pool = MysqlConnPool::ins();
try {
shared_ptr<Connection> con = pool->getConn();
/* 连接 MySQL 数据库 test */
con->setSchema("game");
cout << "con.isClosed() :" << con->isClosed() << endl;
shared_ptr<Statement> stmt(con->createStatement());
shared_ptr<ResultSet> res(stmt->executeQuery("select * from user"));
cout << "row count:" << res->rowsCount() << endl;
while (res->next()) {
cout << "id:" << res->getInt("id") << " name:" << res->getString("name").c_str() << endl;
}
pool->releaseConn(con);
} catch (sql::SQLException &e) {
cout << "ERR:" << e.what() << endl;;
}
cout << endl;
}