how to set mysql_ping timeout with MySQL++
I want mysql_ping to timeout in matter of seconds. In the testcase below if a connection is established followed by "ifconfig eth0 down" the false side of conn.ping() is never reached. The thread/process enters what seems like an endless wait. I want to change this and make it timeout faster, preferably using MySQL++ options. Any idea which option that might be ?
Maybe I also need to set how many times it will retry ?
Reading up on the documentation for MySQL, it tells us mysql_ping will try automatic reconnect. Which is fine but eventually I'd want that to timeout aswell.
http://dev.mysql.com/doc/refman/5.1/en/mysql-options.html http://dev.mysql.com/doc/refman/5.1/en/mysql-ping.html
Since it does automatic reconnect, MYSQL_OPT_CONNECT_TIMEOUT seems like the way to go. However in the testcase below setting mysqlpp::ConnectTimeoutOption(1) 开发者_运维知识库does not help.
Seems like MySQL++ ping() is just a wrapper around the C API, i gathered this from "/usr/include/mysql++/dbdriver.h" which defines ping() as:
bool ping() { return !mysql_ping(&mysql_); }
Versions of the libraries I'm using are:
#include <iostream>
#include <mysql++/mysql++.h>
//g++ -o test -I/usr/include/mysql/ -lmysqlpp testcase_mysql_timeout.cpp
int main(int argc, char *argv[]) {
mysqlpp::Connection conn;
conn = mysqlpp::Connection(true);
try {
conn.set_option(new mysqlpp::MultiStatementsOption(true));
conn.set_option(new mysqlpp::ConnectTimeoutOption(1));
conn.set_option(new mysqlpp::InteractiveOption(true));
}
catch (mysqlpp::BadOption &e) {
std::cerr << "ConnectDB exception: " << e.what() << std::endl;
}
conn.connect("MyDB", "my.dyndns.org", "user", "password", 3306);
while(1) {
if (!conn.ping()) {
std::cout << "Host not reachable. Try to reconnect?" << std::endl;
}
else {
std::cout << "Host is reachable all is good." << std::endl;
}
usleep(1000000);
}
}
I'm afraid I have to answer my own question :)
Reading a bit more of the MySQL documentation gave the answer. Setting the connect timeout in this case does very little. It still has to wait for TCP/IP Close_Wait_Timeout with a default of 10 minutes:
http://dev.mysql.com/doc/refman/5.1/en/mysql-options.html
MYSQL_OPT_READ_TIMEOUT (argument type: unsigned int *)
The timeout in seconds for attempts to read from the server. Each attempt uses this timeout value and there are retries if necessary, so the total effective timeout value is three times the option value. You can set the value so that a lost connection can be detected earlier than the TCP/IP Close_Wait_Timeout value of 10 minutes. Before MySQL 5.1.41, this option applies only to TCP/IP connections and, prior to MySQL 5.1.12, only for Windows.
精彩评论