C + + implements database connection pooling
I try to implement the database connection pool with the new C + + standard, and the code simplifies a lot.
Ideas:
Add a database connection as an object into the list queue, create a queue when the connection pool is created, add custom-sized connection objects, connect objects with smart pointers (DELETE statements should not appear in modern C + +), avoid memory problems like memory leaks, A lambda expression is used on the smart pointer to register the delete delete function to release the connection resource and return it in time (where Std::move is used to transfer the object ownership in the list to the temporary smart pointer object in the function, which is automatically released when it leaves the scope.) )
For a database connection pool introduction, you can look at the following two articles:
Analysis of database connection pool (i)
Analysis of database connection pool (II.)
Code:
mysql_connect.h
#ifndef _mysql_connection_#define _mysql_connection_//c++#include <iostream>#include <string>#include <list>#include <memory>#include <functional>//mysql Driver#include <mysql_driver.h>#include <mysql_connection.h>//mysql Execute#include <cppconn/driver.h>#include <cppconn/statement.h>#include <cppconn/prepared_statement.h>#include <cppconn/resultset.h>#include <exception>//thread Mutex#include <mutex>using namespacesqlusingDelfunc =STD::function<void(connection*) >;classconnectionpool{ Public://Get database Connection pool object static singleton mode Staticconnectionpool* getinstance ();//Get a connection AutoGetConnect ()STD::shared_ptr<Connection>;//Return a connection AutoRetconnect (STD::shared_ptr<Connection> &ret)void; ~connectionpool ();Private: ConnectionPool (STD::stringNameSTD::stringPwdSTD::stringNurl,intMaxSize);//Initialize connection pool AutoInitconnectpool (intInitialSize)void;//Destroy connection pool AutoDestorypool ()void;//destory One connection AutoDestoryoneconn ()void;//Expand database Connection Pool AutoExpandpool (intSize),void;//Shrink database connection pool AutoReducepool (intSize),void;//add Conn AutoAddconn (intSize),void; Public://get size AutoGetpoolsize ()int;Private:STD::stringUsername//Account STD::stringPassword//Password STD::stringUrl//Connection URL intPoolsize;//pool Size //Store all connections STD:: List<std::shared_ptr<Connection>> conlist;StaticConnectionPool *pool;//Connection pool object STD:: Mutex lock;//LockDriver *driver;//mysql Driver};#endif
mysql_connect.cpp
#include <stdio.h>#include <stdlib.h>#include <assert.h>#include "mysql_connect.h"Connectionpool*connectionpool::p ool =nullptr;//private//ConstructorsConnectionpool::connectionpool (STD::stringNameSTD::stringPwdSTD::stringNurl,intMaxSize): Username (name), password (pwd), url (nurl), Poolsize (maxSize) {//Get MySQL driverDriver = Get_driver_instance ();//start to initialize half of sizeInitconnectpool (poolsize/2);}//destructorConnectionpool::~connectionpool () {Destorypool ();}//Get connection Pool sizeintConnectionpool::getpoolsize () {returnConlist.size ();}//Increase connectionvoidConnectionpool::addconn (intSize) { for(inti =0; i < size; ++i) {//Create connectionConnection *conn = driver->connect (URL, username, password);STD::shared_ptr<Connection> SP (conn, [] (Connection *conn) {DeleteConn }); Conlist.push_back (STD:: Move (sp)); }}//Initialize connection poolvoidConnectionpool::initconnectpool (intInitialSize) {//Locking, add a connection STD::lock_guard<STD::mutex> Locker (lock); Addconn (initialsize);}//Destroy a connectionvoidConnectionPool::d estoryoneconn () {//Smart pointer plus std::move transfer "ownership" of a connection, when out of scope, automatically call Close connect STD::shared_ptr<Connection> &&SP =STD:: Move (Conlist.front ()); Sp->close (); --poolsize;}//Destroy entire connection poolvoidConnectionPool::d Estorypool () { for(Auto&conn:conlist) {//Transfer ownership, when out of scope, close connection, smart pointer automatically releases when out of scope STD::shared_ptr<Connection> &&SP =STD:: Move (Conlist.front ()); Sp->close (); }}//Enlarge connection PoolvoidConnectionpool::expandpool (intSize) {STD::lock_guard<STD::mutex> Locker (lock); Addconn (size); Poolsize + = size;}//Reduce connection poolvoidConnectionpool::reducepool (intSize) {STD::lock_guard<STD::mutex> Locker (lock);//reduced size cannot exceed the size of storage if(Size > Poolsize) {return; } for(inti =0; i < size; i++) {//sp point New Object, old object releaseDestoryoneconn (); } poolsize-= size;}//public//Get connection Pool instanceConnectionpool*connectionpool::getinstance () {if(Pool = =nullptr) {//3306 is a MySQL-occupied port that actually creates 40 connectionsPool =NewConnectionPool ("Root","********","tcp://127.0.0.1:3306", +); }returnPool;}//Get a connectionSTD::shared_ptr<connection>connectionpool::getconnect () {STD::lock_guard<STD::mutex> Locker (lock);STD::shared_ptr<Connection> sp = Conlist.front (); Conlist.pop_front ();returnSP;}//Return a connectionvoidConnectionpool::retconnect (STD::shared_ptr<Connection> &ret) {STD::lock_guard<STD:: Mutex>locker (lock); Conlist.push_back (ret);}
try.cpp
#include <stdio.h>#include <stdlib.h>#include <assert.h>#include <mysql_connect.h>#include <unistd.h>ConnectionPool *pool = Connectionpool::getinstance ();intMainintargcChar*argv[]) {STD::shared_ptr<Connection>con; Statement *state; ResultSet *result;//Get a connectioncon = Pool->getconnect ();//Get a database connection objectState = Con->createstatement ();//Use xl_db this databaseState->execute ("Use xl_db");//Query Statementsresult = State->executequery ("SELECT * from UserInfo;"); while(Result->next ()) {intid = result->getint ("UID");STD::stringName = Result->getstring ("Password");STD::cout<<"ID:"<< ID <<"Name:"<< name <<STD:: Endl; } Sleep (Ten); Pool->retconnect (con);STD::cout<< pool->getpoolsize () <<STD:: Endl; SleepTen);returnexit_success;}
I tested myself, created a database connection pool, called an object, then performed a database connection, queried the results, and then returned a connection.
创建连接池前
创建连接池后
Id 792 is the connection I called, and then I perform a query operation, so the DB shows the connection on the xl_db.
This is your own write a simple database connection pool, you can refer to, if you want to use the words also need to change their own.
These xx pools, such as thread pool, process pool, connection pooling principle are similar, is to create a batch of objects, and then a queue to save, when needed to take, use the return on the line, and then through the c++11 new features and so we can improve performance and security and the introduction of the program, such as the std:: Move and smart pointers, lambda, and more.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + Implements database connection pooling