MySQL 连接中 IP 或端口错误导致连接超时的解决方案

  在 Visual Studio 中调用 mysql_real_connect() 函数连接 MySQL 过程中,当仅有连接 IP 错误时,会存在大概 20 秒的连接超时,最后连接失败;当有连接端口错误时,会存在大概 60 秒连接超时,最后连接失败。

  通过在 mysql_real_connect() 前配置以下函数:

  mysql_options(handle, MYSQL_OPT_CONNECT_TIMEOUT, timeOut)

  但并不能成功在超时时间之后,结束连接请求。

  这里提供一种线程解决方案,如下:

 1 struct MySqlConnOpts_t
 2 {
 3     MYSQL* pConnHandle;
 4     std::string strIp;
 5     std::string strUserName;
 6     std::string strPassWord;
 7     int nPort;
 8     int nErrNum;
 9 
10     MySqlConnOpts_t()
11     {
12         pConnHandle = NULL;
13         strIp = "";
14         strUserName = "";
15         strPassWord = "";
16         nPort = -1;
17         nErrNum = -1;
18     }
19 };
20 
21 MySqlConnOpts_t* pConnectOptions = new MySqlConnOpts_t;
22 // pConnectOptions 中 pConnHandle、strIp、strUserName、strPassWord、nPort 的初始化;
23 
24 DWORD WINAPI mysqlConnect(LPVOID lpParam)
25 {
26     DWORD ret = 0;
27     MySqlConnOpts_t* pConnOpts = static_cast<MySqlConnOpts_t*>(lpParam);
28 
29     if(NULL == mysql_real_connect(pConnOpts->pConnHandle, pConnOpts->strIp , pConnOpts->strUserName, pConnOpts->strPassWord, pConnOpts->nPort, NULL, CLIENT_MULTI_STATEMENTS))
30     {
31           ret = -1;
32     }
33 
34     pConnOpts->nErrNum = ret;
35 
36     return ret;
37 }
38 
39 const int nTimeOut = 1000;  // 超时设置,单位为 ms;
40 HANDLE hThread = CreateThread(NULL, 0, mysqlConnect, pConnectOptions, 0, NULL);
41 DWORD dwRet = WaitForSingleObject(hThread, nTimeOut);
42 CloseHandle(hThread);
43 
44 if(0 != dwRet)
45 {
46     // 处理超时逻辑;
47 }
48 
49 if(0 != pConnectOptions->nErrNum)
50 {
51     // 处理错误连接逻辑
52 }
53 
54 // 处理 pConnectOptions 指针;

   可以解决连接超时问题。

猜你喜欢

转载自www.cnblogs.com/dishengAndziyu/p/12172795.html