使用boost::circular_buffer_space_optimized实现OTL数据库连接池

来源:互联网 发布:淘宝上的吉他店 编辑:程序博客网 时间:2024/06/07 04:59

引言

数据库连接是一种关键的有限的昂贵的资源,因此对数据库连接的管理能显著影响到整个应用程序的伸缩性和健壮性,影响到程序的性能指标。数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而再不是重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。这项技术能明显提高对数据库操作的性能。


数据库连接池的关键因素

1.容器

数据库连接池是数据库连接的集合,必须要有容器来存储这些连接,许多方法都是用stl的list、queue、vector常用的容器来实现的,但今天我选择了circular_buffer_space_optimized来实现,具体介绍可到www.boost.org上查看。

2.最小连接数

数据库连接池在初始化时将创建一定数量的数据库连接放到连接池中,这些数据库连接的数量是由最小数据库连接数来设定的。无论这些数据库连接是否被使用,连接池都将一直保证至少拥有这么多的连接数量。

3.最大连接数

连接池的最大数据库连接数量限定了这个连接池能占有的最大连接数,当应用程序向连接池请求的连接数超过最大连接数量时,这些请求将被加入到等待队列中。

4.连接的使用

最先的连接请求将会获利,之后超过最小连接数量的连接请求等价于建立一个新的数据库连接。不过,这些大于最小连接数的数据库连接在使用完不会马上被释放,它将被放到连接池中等待重复使用或是空闲超时后被释放。获得连接的请求使用完之后,要把连接放回容器当中,以便之后的请求重复使用,达到重复利用的目的。

实现代码

当然,我也不完全按照上面的主要因素来实现的,可根据circular_buffer_space_optimized和OTL的特性实现了一个简单的数据库连接池。

//数据库连接池虚类db_conn_pool.h

[cpp] view plaincopyprint?
  1. #pragma once  
  2.   
  3. #include <iostream>  
  4. #include <boost/circular_buffer.hpp>  
  5. #include <boost/shared_ptr.hpp>  
  6. #include <boost/thread/mutex.hpp>  
  7.   
  8. template <class conn>  
  9. class db_conn_pool  
  10. {  
  11. public:  
  12.     typedef conn connection;  
  13.     typedef boost::shared_ptr<conn> connection_ptr;  
  14.   
  15.     virtual connection_ptr getConnection() = 0;  
  16.     virtual void initConnection() = 0;  
  17.     int size(){return m_conn_container.size();}  
  18.       
  19. protected:  
  20.     std::string m_conn_str;  
  21.     unsigned short m_max_size;  
  22.   
  23.     boost::circular_buffer_space_optimized<connection_ptr> m_conn_container;  
  24.     boost::mutex m_mutex;  
  25.   
  26.     db_conn_pool(){}  
  27.     db_conn_pool(const std::string& conn_str, unsigned short max_size)  
  28.         :m_conn_str(conn_str), m_max_size(max_size)  
  29.     {  
  30.   
  31.     }  
  32.   
  33.     virtual connection_ptr createConnection() = 0;  
  34. };  
  35.   
  36. template<class conn_pool, class conn>  
  37. class connection_wrap{  
  38. public:  
  39.     connection_wrap(conn_pool& pool, boost::shared_ptr<conn> ptrConn)  
  40.         :m_pool(pool), m_ptrConn(ptrConn)  
  41.     {  
  42.   
  43.     }  
  44.   
  45.     ~connection_wrap()  
  46.     {  
  47.         m_pool.releaseConnection(m_ptrConn);  
  48.     }  
  49.   
  50. private:  
  51.     boost::shared_ptr<conn> m_ptrConn;  
  52.     conn_pool& m_pool;  
  53. };  

//mysql数据库连接池my_conn_pool.h

[cpp] view plaincopyprint?
  1. #pragma once  
  2. #include <iostream>  
  3. #define OTL_ODBC // CompileOTL 4.0/ODBC    
  4. // Thefollowing #define is required with MyODBC 5.1 and higher    
  5. #define OTL_ODBC_SELECT_STM_EXECUTE_BEFORE_DESCRIBE    
  6. #define OTL_STL  
  7. #include "otlv4.h"  
  8. #include "db_conn_pool.h"  
  9. #include <boost/format.hpp>  
  10. #include <firebird/log/logger_log4.hpp>  
  11.   
  12. //FUNC DEFINE  
  13. #define OTL_STREAM                      _otl_stream  
  14. #define OTL_EOF                         _otl_stream.eof()  
  15. #define OTL_SUCCEED                     0                         
  16. #define OTL_FAILED                      -1  
  17. #define OTL_NO_DATA_FOUND               1403      
  18. #define OTL_BEGIN(conn, sql)                    \  
  19.     try {                                           \  
  20.         LOG4CXX_DEBUG(console_log, KDS_CODE_INFO << sql);     \  
  21.         otl_stream _otl_stream(100, sql, *conn);             
  22.   
  23. #define OTL_END(conn, _count)   \  
  24.         _otl_stream.flush();                                    \  
  25.         _count = _otl_stream.get_rpc();                         \  
  26.     } catch (otl_exception& otl_exp) {                          \  
  27.         print_exception(otl_exp);                   \  
  28.         if(otl_exp.code == 2006)                    \  
  29.         {                                           \  
  30.             conn->logoff();                          \  
  31.         }                                           \  
  32.         throw business_error(otl_exp.code, (char*)(otl_exp.msg));   \  
  33.     }  
  34.   
  35. #define OTL_COMMIT(conn) conn->commit();  
  36.   
  37. #define OTL_ROLLBACK(conn) conn->rollback();  
  38.   
  39.   
  40. static void print_exception(otl_exception& otl_exp)  
  41. {  
  42.     boost::format fmt("otl with exception:[%1%][%2%][%3%]");  
  43.     std::string str = boost::str(fmt   
  44.         % otl_exp.code  
  45.         % otl_exp.msg  
  46.         % otl_exp.stm_text);  
  47.     LOG4CXX_ERROR(console_log, KDS_CODE_INFO << str);  
  48. }  
  49.   
  50. class mysql_conn_pool : public db_conn_pool<otl_connect>  
  51. {  
  52. public:  
  53.     ~mysql_conn_pool();  
  54.     static mysql_conn_pool& getInstance();  
  55.     void setParam(const std::string& conn_str, unsigned short max_size);  
  56.   
  57.     connection_ptr getConnection();  
  58.     void releaseConnection(connection_ptr ptrConn);  
  59.     void initConnection();  
  60.   
  61. protected:  
  62.     typedef db_conn_pool<otl_connect> super;  
  63.     mysql_conn_pool();  
  64. private:  
  65.     connection_ptr createConnection();  
  66. };  

//my_conn_pool.cpp

[cpp] view plaincopyprint?
  1. #include "mysql_conn_pool.h"  
  2. #include <boost/typeof/typeof.hpp>  
  3.   
  4. mysql_conn_pool::mysql_conn_pool()  
  5. {  
  6.   
  7. }  
  8.   
  9. mysql_conn_pool::~mysql_conn_pool()  
  10. {  
  11.   
  12. }  
  13.   
  14. mysql_conn_pool& mysql_conn_pool::getInstance()  
  15. {  
  16.     static mysql_conn_pool pool;  
  17.     return pool;  
  18. }  
  19.   
  20. void mysql_conn_pool::setParam(const std::string& conn_str, unsigned short max_size)  
  21. {  
  22.     m_conn_str = conn_str;  
  23.     m_max_size = max_size;  
  24. }  
  25.   
  26. void mysql_conn_pool::initConnection()  
  27. {  
  28.     m_conn_container.resize(m_max_size);  
  29.     otl_connect::otl_initialize(1); // initialize the database API environment  
  30.   
  31.     for (int i = 0; i < m_max_size; ++i)  
  32.     {  
  33.         createConnection();  
  34.     }  
  35. }  
  36.   
  37. mysql_conn_pool::connection_ptr mysql_conn_pool::getConnection()  
  38. {  
  39.     connection_ptr ptrConn;  
  40.   
  41.     std::time_t begin;  
  42.     std::time(&begin);  
  43.   
  44.     while(1)  
  45.     {  
  46.         boost::mutex::scoped_lock lock(m_mutex);  
  47.   
  48.         if (m_conn_container.size() == 0)  
  49.         {  
  50.             std::time_t now;  
  51.             std::time(&now);  
  52.             if (now - begin > 10)  
  53.             {  
  54.                 /* 
  55.                 *若超过10秒还没取得连接对象,则认为连接池里的连接都失效用完, 
  56.                 *应重新创建 
  57.                 */  
  58.                 createConnection();  
  59.                 begin = now;  
  60.             }  
  61.             continue;  
  62.         }  
  63.   
  64.         ptrConn = m_conn_container.front();  
  65.         m_conn_container.pop_front();  
  66.   
  67.         if (ptrConn != NULL && ptrConn->connected)  
  68.         {  
  69.             /*BOOST_AUTO(pos, m_conn_container.begin()); 
  70.             m_conn_container.rotate(++pos);*/  
  71.   
  72.             break;  
  73.         }  
  74.         else  
  75.         {  
  76.             //m_conn_container.pop_front();  
  77.             createConnection();  
  78.             continue;;  
  79.         }  
  80.     }  
  81.   
  82.     return ptrConn;  
  83. }  
  84.   
  85. mysql_conn_pool::connection_ptr mysql_conn_pool::createConnection()  
  86. {  
  87.     connection_ptr ptrConn(new otl_connect());  
  88.     ptrConn->rlogon(m_conn_str.c_str());  
  89.   
  90.     if (ptrConn != NULL && ptrConn->connected)  
  91.     {  
  92.         ptrConn->auto_commit_on();  
  93.         ptrConn->set_timeout(60);  
  94.         m_conn_container.push_back(ptrConn);  
  95.     }  
  96.   
  97.     return ptrConn;  
  98. }  
  99.   
  100. void mysql_conn_pool::releaseConnection(connection_ptr ptrConn)  
  101. {  
  102.     boost::mutex::scoped_lock lock(m_mutex);  
  103.     if (ptrConn != NULL  && ptrConn->connected)  
  104.     {  
  105.         m_conn_container.push_back(ptrConn);  
  106.     }  
  107. }  

//测试test.cpp

[cpp] view plaincopyprint?
  1. #include <iostream>  
  2. #include "my_conn_pool.h"  
  3.   
  4. int main()  
  5. {  
  6.     mysql_conn_pool& m_mysql_pool = mysql_conn_pool::getInstance();  
  7.     m_mysql_pool.setParam("Driver={MySQL ODBC 5.2w Driver};Server=127.0.0.1;Port=3306;Database=opensips;Uid=root;Pwd=123321", 10);  
  8.     m_mysql_pool.initConnection();  
  9.     mysql_conn_pool::connection_ptr pConn = m_mysql_pool.getConnection();  
  10.     connection_wrap<mysql_conn_pool, mysql_conn_pool::connection> wrap(m_mysql_pool, pConn);  
  11.     std::string sql;  
  12.     sql = "delete from account_bind where ext_acct = :f1<char[50]>";  
  13.   
  14.     int count = 0;  
  15.     OTL_BEGIN(pConn, sql.c_str());  
  16.     OTL_STREAM << req.sExtAcct;  
  17.     OTL_END(pConn, count);  
  18.     return 0;