Skip to content

Commit

Permalink
Merge pull request TarsCloud#152 from wincsb/release/2.4
Browse files Browse the repository at this point in the history
set timeout options to prevent "connnect", "real_query" to be blocked for tens of minutes
  • Loading branch information
ruanshudong authored Mar 4, 2021
2 parents cf229e2 + d7adcb0 commit 2966d38
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 7 deletions.
38 changes: 31 additions & 7 deletions util/include/util/tc_mysql.h
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,18 @@ struct TC_DBConf
*/
int _flag;

/**
* 连接超时
* Port
*/
int _connectTimeout;

/**
* 读写超时
* Port
*/
int _writeReadTimeout;

/**
* @brief 构造函数
* @brief Constructor
Expand Down Expand Up @@ -125,18 +137,30 @@ struct TC_DBConf
{
map<string, string> mpTmp = mpParam;

_host = mpTmp["dbhost"];
_user = mpTmp["dbuser"];
_password = mpTmp["dbpass"];
_database = mpTmp["dbname"];
_charset = mpTmp["charset"];
_port = atoi(mpTmp["dbport"].c_str());
_flag = 0;
_host = mpTmp["dbhost"];
_user = mpTmp["dbuser"];
_password = mpTmp["dbpass"];
_database = mpTmp["dbname"];
_charset = mpTmp["charset"];
_port = atoi(mpTmp["dbport"].c_str());
_flag = 0;
_connectTimeout = atoi(mpTmp["connectTimeout"].c_str());
_writeReadTimeout = atoi(mpTmp["writeReadTimeout"].c_str());

if(mpTmp["dbport"] == "")
{
_port = 3306;
}

if(mpTmp["connectTimeout"] == "")
{
_connectTimeout = 5;
}

if(mpTmp["writeReadTimeout"] == "")
{
_writeReadTimeout = 15;
}
}

};
Expand Down
20 changes: 20 additions & 0 deletions util/src/tc_mysql.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,26 @@ void TC_Mysql::connect()
}


//设置连接超时
if(_dbConf._connectTimeout > 0) {
if (mysql_options(_pstMql, MYSQL_OPT_CONNECT_TIMEOUT, &_dbConf._connectTimeout)) {
throw TC_Mysql_Exception(string("TC_Mysql::connect: mysql_options MYSQL_OPT_CONNECT_TIMEOUT ") + TC_Common::tostr(_dbConf._connectTimeout) + ":" + string(mysql_error(_pstMql)));
}
}


if(_dbConf._writeReadTimeout > 0) {
//设置读超时
if (mysql_options(_pstMql, MYSQL_OPT_READ_TIMEOUT, &_dbConf._writeReadTimeout)) {
throw TC_Mysql_Exception(string("TC_Mysql::connect: mysql_options MYSQL_OPT_READ_TIMEOUT ") + TC_Common::tostr(_dbConf._writeReadTimeout) + ":" + string(mysql_error(_pstMql)));
}
//设置写超时
if (mysql_options(_pstMql, MYSQL_OPT_WRITE_TIMEOUT, &_dbConf._writeReadTimeout)) {
throw TC_Mysql_Exception(string("TC_Mysql::connect: mysql_options MYSQL_OPT_WRITE_TIMEOUT ") + TC_Common::tostr(_dbConf._writeReadTimeout) + ":" + string(mysql_error(_pstMql)));
}
}


if (mysql_real_connect(_pstMql, _dbConf._host.c_str(), _dbConf._user.c_str(), _dbConf._password.c_str(), _dbConf._database.c_str(), _dbConf._port, NULL, _dbConf._flag) == NULL)
{
throw TC_Mysql_Exception("[TC_Mysql::connect]: mysql_real_connect: " + string(mysql_error(_pstMql)));
Expand Down

0 comments on commit 2966d38

Please sign in to comment.