基于C++“简单且有效”的“数据库连接池”

server/2025/3/2 1:22:25/

前言

  • 数据库连接池在开发中应该是很常用的一个组件,他可以很好的节省连接数据库的时间开销;
  • 本文基使用C++实现了一个简单的数据库连接池,代码量只有400行左右,但是压力测试效果很好
  • 欢迎收藏 + 关注,本人将会持续更新后端与AI算法有关知识点

文章目录

      • 连接池功能点介绍
        • 初始连接量
        • 最大连接量
        • 最大空闲时间
        • 连接超时时间
      • 连接池主要包含了以下功能点
      • 代码
      • 压力测试

MySQL 数据库是基于 C/S 模式的,在每一次访问mysql服务器的时候,都需要建立一个TCP连接但是,在高并发情况下,大量的 TCP 三次握手、MySQL Server 连接认证、MySQL Server 关闭连接回收资源和 TCP 四次挥手所耗费的性能事件也是很明显的,故设置连接池就是为了减少这一部分的性能损耗

连接池功能点介绍

初始连接量

表示连接池事先会和 MySQL Serve r创建最小个数的连接,当应用发起 MySQL 访问时,不用再创建和 MySQL Server 新的连接,直接从连接池中获取一个可用的连接即可,使用完成后并不去释放连接,而是把连接再归还到连接池当中

最大连接量

当并发访问MySQL Server的请求增多时,初始连接量已经不够用了,此时会去创建更多的连接给应用去使用,是新创建的连接数量上限是maxSize,不能无限制的创建连接。并且当这些连接使用完之后,再次归还到连接池当中来维护。

最大空闲时间

当访问MySQL的并发请求多了以后,连接池里面的连接数量会动态增加,上限是maxSize 个,当这些连接用完会再次归还到连接池当中。如果在指定的时间内这些新增的连接都没有被再次使用过,那么新增加的这些连接资源就要被回收掉,只需要保持初始连接量个连接即可

连接超时时间

当MySQL的并发请求量过大,连接池中的连接数量已经到达最大数量了,而此时没有空闲的连接可供使用,那么此时应用从连接池获取连接无法成功,它通过阻塞的方式获取连接的时间,如果超过一个时间,那么获取连接失败

连接池主要包含了以下功能点

  • 单例模式设置连接池;
  • 向用户提供一个接口,可以从池中拿到一个数据库连接;
  • 采用生产者-消费者模式,池用队列作为缓冲区,实现生成连接和拿取连接;
  • 采用锁,在创建、拿取连接中进行加锁;
  • 采用智能指针管理从队列中获取的连接,并且采用lambda实现智能指针的析构函数,将连接从新放回队列中;
  • 设置生产连接、回收连接线程,并且驻留后台,作为守护线程;
  • 采用原子变量才记录当前池中的连接数。

创建目录如下

在这里插入图片描述

代码

logger.h

#ifndef PUBLIC_H_
#define PUBLIC_H_#include <iostream>// 作用:封装简单的LOG
#define LOGGER(str) std::cout << "====》" << __LINE__ << " time: " << __TIME__ << " message: " << str << std::endl;#endif // !PUBLIC_H_

connection.h

#ifndef CONNECTION_H_
#define CONNECTION_H_#include <mysql/mysql.h>
#include <ctime>
#include <string>/*
功能:初始化数据库连接释放连接连接数据库查询mysql修改数据库数据刷新/设置空闲时间的起始时间点返回空闲时间
*/class Connection
{
public:// 初始化数据库连接Connection();// 释放连接~Connection();// 连接数据库bool connectionSqlBase(std::string ip, unsigned int port, std::string user, std::string passward, std::string dbName);// 查询mysqlMYSQL_RES* query(std::string sql);// 修改数据库数据bool modify(std::string sql);// 刷新/设置空闲时间的起始时间点void setStartActivateTime();// 返回空闲时间clock_t getActivateTime();
private: MYSQL* m_sqlConn{};   // 连接mysql服务器clock_t m_activateTime;  // 记录空闲时间的起始点
};#endif // !CONNECTION_H_

connection.cpp

#include "connection.h"
#include "logger.h"// 初始化数据库连接
Connection::Connection()
{m_sqlConn = mysql_init(nullptr);if(m_sqlConn == nullptr) {LOGGER("mysql init false !!!");return;}
}
// 释放连接
Connection::~Connection()
{mysql_close(m_sqlConn);
}
// 连接数据库
bool Connection::connectionSqlBase(std::string ip, unsigned int port, std::string user, std::string passward, std::string dbName)
{if(nullptr == mysql_real_connect(m_sqlConn, ip.c_str(), user.c_str(), passward.c_str(), dbName.c_str(), port, NULL, 0)) {LOGGER("mysql connects error!!");return false;}return true;
}
// 查询mysql
MYSQL_RES* Connection::query(std::string sql)
{int res = mysql_query(m_sqlConn, sql.c_str());if(0 != res) {LOGGER("sql query false!!!");return nullptr;}return mysql_use_result(m_sqlConn);
}
// 修改数据库数据
bool Connection::modify(std::string sql)
{int res = mysql_query(m_sqlConn, sql.c_str());if(0 != res) {LOGGER("sql update/insert/select false!!!");return false;}return true;
}
// 刷新/设置空闲时间的起始时间点
void Connection::setStartActivateTime()
{m_activateTime = clock();
}
// 返回空闲时间
clock_t Connection::getActivateTime()
{return clock() - m_activateTime;
}

dbConnectionPool.h

#ifndef DBCONNECTION_H_
#define DBCONNECTION_H_#include "connection.h"
#include <mysql/mysql.h>
#include <queue>
#include <string>
#include <condition_variable>
#include <atomic>
#include <memory>// 核心:生产者、消费者模式class DbConnPool
{
public: // 单例模式static DbConnPool* getDbConnPool();// 对外提供接口: 获取连接的数据库,通过智能指针回收std::shared_ptr<Connection> getMysqlConn();// 测试// void test()// {//     readConfigurationFile();// }private: // 单例模型:构造函数私有化, 目的:创建最小连接数量DbConnPool();DbConnPool(const DbConnPool&) = delete;DbConnPool operator=(const DbConnPool&) = delete;// 读取配置文件bool readConfigurationFile();// 如果没有Mysql连接了,则产生新连接,这个线程驻留后台(像守护线程一样)void produceNewConn();// 如果队列线程 > initSize, 且空闲时间大于最大空闲时间,则回收void recycleConn();private:// MYSQL连接信息std::string m_ip;unsigned int m_port;std::string m_username;std::string m_password;std::string m_dbname;// 数据库连接池信息int m_initSize;int m_maxSize;int m_maxFreeTime;int m_maxConnTime;// 生产者、消费者共享内存:获取连接std::queue<Connection*> m_connQueue;// 存储当前存储到队列中存储的数量std::atomic_int m_conntionCnt{};// 锁std::mutex m_queueMuetx;// 生产者、消费者:产生连接和取连接std::condition_variable m_cv;  // 用于生产线程和消费线程之间的通信
};#endif // !DBCONNECTION_H_

dbConnectionPool.cpp

#include "dbConnectionPool.h"
#include "connection.h"
#include "logger.h"#include <iostream>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <thread>
#include <functional>
#include <chrono>// 创建连接:new,但是拿取连接后是交给shared_ptr// 单例模式
DbConnPool* DbConnPool::getDbConnPool()
{// 最简单的方式:staticstatic DbConnPool pool;return &pool;
}// 对外提供接口: 获取连接的数据库,通过智能指针回收
std::shared_ptr<Connection> DbConnPool::getMysqlConn()
{std::unique_lock<std::mutex> lock(m_queueMuetx);// 判断队列是否为空while(m_connQueue.empty()) {// 队列为空,则等待 最大连接时间, 即这个时候客户端请求连接,但是池里没有连接了,则会等待,如果超过了最大时间,则:连接失败if(std::cv_status::timeout == m_cv.wait_for(lock, std::chrono::seconds(m_maxConnTime))) {// 再次判断是否为空if(m_connQueue.empty()) {LOGGER("no conntion !!!!");return nullptr;}}}/*从队列中获取一个连接,交给**智能指针管理**注意:删除连接有回收线程监控,而这里获取的连接使用完后,需要还给**队列中**,所以**需要重写智能指针的回收函数***/std::shared_ptr<Connection> sp(m_connQueue.front(), [&](Connection* pconn){// 注意,这里需要加锁std::unique_lock<std::mutex> lock(m_queueMuetx);pconn->setStartActivateTime();m_connQueue.push(pconn);  // 入队m_conntionCnt++;   // +1});// 弹出队列m_connQueue.pop();m_conntionCnt--;   // -1return sp;
}// 单例模型:构造函数私有化
DbConnPool::DbConnPool()
{if(readConfigurationFile() == false) {return;}std::unique_lock<std::mutex> lock(m_queueMuetx);for(int i = 0; i < m_maxSize; i++) {Connection* newConn = new Connection();newConn->connectionSqlBase(m_ip, m_port, m_username, m_password, m_dbname);newConn->setStartActivateTime();   // 设置 空闲时间 的起始点m_connQueue.push(newConn);      // 入队m_conntionCnt++;     // 存储到队列中数据+1}// 开启线程:检查是否需要需要**新创建连接**std::thread produce(std::bind(&DbConnPool::produceNewConn, this));produce.detach();   // 驻留后台// 开启线程,检查是否需要**删除连接**std::thread search(std::bind(&DbConnPool::recycleConn, this));search.detach();    // 驻留后台
}// 读取配置文件
bool DbConnPool::readConfigurationFile()
{FILE* fp = fopen("./mysql.ini", "r");if(fp == nullptr) {LOGGER("mysql.ini open false!!");return false;}char buff[BUFSIZ] = { 0 };while(!feof(fp)) {// clearmemset(buff, 0, sizeof(buff));// 读取fgets(buff, BUFSIZ, fp);std::string str = buff;// 判空if(str.empty()) {continue;}// 截断int idx = str.find('=', 0);if(idx == -1) {continue;}int end = str.find('\n', idx);std::string key = str.substr(0, idx);std::string value = str.substr(idx + 1, end - idx - 1);//std::cout << "key: " << key << " value: " << value << std::endl;if(key == "ip") {m_ip = value;} else if(key == "port") {m_port = atoi(value.c_str());} else if(key == "username") {m_username = value;} else if(key == "password") {m_password = value;} else if(key == "dbname") {m_dbname = value;} else if(key == "initSize") {m_initSize = atoi(value.c_str());} else if(key == "maxSize") {m_maxSize = atoi(value.c_str());} else if(key == "maxFreeTime") {m_maxFreeTime = atoi(value.c_str());} else if(key == "maxConnTime") {m_maxConnTime = atoi(value.c_str());}}std::cout << m_ip << " " << m_port << " " << m_username << " " << m_password << " " << m_dbname << " " << m_initSize << " " << m_maxSize << " " << m_maxFreeTime << " " << m_maxConnTime << std::endl;return true;
}// 如果池里没有Mysql连接了,则产生新连接,这个线程驻留后台(像守护线程一样)
/*
实现思路:设置一个循环:循环检查如果队列不为空,则条件变量一直等待
*/
void DbConnPool::produceNewConn()
{for(;;) {std::unique_lock<std::mutex> lock(m_queueMuetx);while(!m_connQueue.empty()) {m_cv.wait(lock);    // 条件变量一直等待}// 这个时候,队列为空,从新创建连接for(int i = 0; i < m_maxSize; i++) {Connection* newConn = new Connection();newConn->setStartActivateTime();   // 刷新时间m_connQueue.push(newConn);m_conntionCnt++;   // +1}// 通知等待线程m_cv.notify_all();}
}// 如果队列线程 > initSize, 且空闲时间大于最大空闲时间,则回收
void DbConnPool::recycleConn()
{for(;;) {std::unique_lock<std::mutex> lock(m_queueMuetx);while(m_conntionCnt > m_initSize) {Connection* conn = m_connQueue.front();// 超过最大空闲时间if((static_cast<double>(conn->getActivateTime()) / CLOCKS_PER_SEC) > m_maxFreeTime) {m_connQueue.pop();m_conntionCnt--;delete conn;} else {   // 对头没超过,则直接退出break;}}}
}

压力测试

分别插入10000条数据,对没有使用连接池和使用连接池分别进行测试。

#include "dbConnectionPool.h"
#include "connection.h"
#include <iostream>
#include <mysql/mysql.h>
#include <chrono>int main() {auto start = std::chrono::high_resolution_clock::now(); // 获取当前时间点for(int i = 0; i < 10000; i++) {
#if 1DbConnPool* pool = DbConnPool::getDbConnPool();std::shared_ptr<Connection> conn = pool->getMysqlConn();char sql[1024] = { 0 };sprintf(sql, "insert into temp(name, age, sex) values('%s', '%d', '%s');", "yxz", 18, "man");conn->modify(sql);
#elif  0Connection conn;conn.connectionSqlBase("127.0.0.1", 3306, "root", "wy2892586", "test");char sql[1024] = { 0 };sprintf(sql, "insert into temp(name, age, sex) values('%s', '%d', '%s');", "yxz", 18, "man");conn.modify(sql);
#endif}auto end = std::chrono::high_resolution_clock::now(); // 获取结束时间点std::chrono::duration<double, std::milli> duration = end - start; // 计算持续时间,并转换为毫秒std::cout << "Time: " << duration.count() << " ms" << std::endl;return 0;
}

结果如下

在这里插入图片描述


http://www.ppmy.cn/server/171670.html

相关文章

Spring全部注解

Spring中的注解主要分为两类&#xff1a; **类级别的注解&#xff1a;**如Component、Repository、Controller、Service以及JavaEE6的ManagedBean和Named注解&#xff0c;都是添加在类上面的类级别注解。 **类内部的注解&#xff1a;**如Bean、Autowire、Value、Resource以及…

BUG: 解决新版本SpringBoot3.4.3在创建项目时勾选lombok但无法使用的问题

前言 当使用Spring Boot 3.4.3创建新项目时&#xff0c;即使正确勾选Lombok依赖&#xff0c;编译时仍出现找不到符号的错误&#xff0c;但代码中Lombok注解的使用完全正确。 原因 Spring Boot 3.4.3在自动生成的pom.xml中新增了maven-compiler-plugin的配置&#xff0c;该插件…

【MySQL】第十一弹---复合查询全攻略:多表、自连接、子查询与合并查询

✨个人主页&#xff1a; 熬夜学编程的小林 &#x1f497;系列专栏&#xff1a; 【C语言详解】 【数据结构详解】【C详解】【Linux系统编程】【MySQL】 目录 1. 复合查询 1.1 基本查询回顾 1.2 多表查询 1.3 自连接 1.4 子查询 1.4.1 单行子查询 1.4.2 多行子查询 1.4.…

【MySQL】 数据类型

欢迎拜访&#xff1a;-CSDN博客 本篇主题&#xff1a;【MySQL】 数据类型 发布时间&#xff1a;2025.1.27 隶属专栏&#xff1a;MySQL 目录 数据类型分类数值类型 tinyint类型 数值越界测试结果说明 bit类型 基本语法使用注意事项 小数类型 float 语法使用注意事项 decimal 语…

vue el-table-column 单元表格的 省略号 实现

要对 el-table-column 的某一列中的每个单元格值进行处理&#xff0c;使其在文本内容超出指定宽度时显示省略号&#xff08;…&#xff09;&#xff0c;可以通过以下方法实现&#xff1a; 使用 scoped slots&#xff1a;利用 Element UI 提供的 scoped slots 自定义单元格内容…

【华为OD机考】华为OD笔试真题解析(16)--微服务的集成测试

题目描述 现在有n个容器服务&#xff0c;服务的启动可能有一定的依赖性&#xff08;有些服务启动没有依赖&#xff09;&#xff0c;其次&#xff0c;服务自身启动加载会消耗一些时间。 给你一个 n n n \times n nn的二维矩阵useTime&#xff0c;其中useTime[i][i]10表示服务…

Java集合性能优化面试题

Java集合性能优化面试题 初始化优化 Q1: 如何优化集合的初始化&#xff1f; public class CollectionInitializationExample {// 1. 合理设置初始容量public void initializationOptimization() {// 不好的实践&#xff1a;使用默认容量List<String> badList new Arr…

如何利用爬虫获取淘宝评论API接口:技术解析与实战指南

在电商领域&#xff0c;商品评论数据是商家优化产品、提升用户体验以及进行市场分析的关键资源。淘宝作为国内领先的电商平台&#xff0c;提供了丰富的API接口&#xff0c;允许开发者通过编程方式获取商品评论信息。本文将详细介绍如何利用Python爬虫技术调用淘宝评论API接口&a…