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 
23  if(NULL != pConnectOptions)
24  {
25       // 進行 pConnectOptions 中 pConnHandle、strIp、strUserName、strPassWord、nPort 的配置操作;
26  }
27  else
28  {
29      // 內存申請失敗操作;
30  }
31 
32  
33  DWORD WINAPI mysqlConnect(LPVOID lpParam)
34  {
35      DWORD ret = 0;
36      MySqlConnOpts_t* pConnOpts = static_cast<MySqlConnOpts_t*>(lpParam);
37  
38      if(NULL == mysql_real_connect(pConnOpts->pConnHandle, pConnOpts->strIp , pConnOpts->strUserName, pConnOpts->strPassWord, pConnOpts->nPort, NULL, CLIENT_MULTI_STATEMENTS))
39      {
40            ret = -1;
41      }
42  
43      pConnOpts->nErrNum = ret;
44  
45      return ret;
46  }
47 
48  const int nTimeOut = 1000;  // 超時設置,單位為 ms;
49  HANDLE hThread = CreateThread(NULL, 0, mysqlConnect, pConnectOptions, 0, NULL);
50  DWORD dwRet = WaitForSingleObject(hThread, nTimeOut);
51  CloseHandle(hThread);
52  
53  if(0 != dwRet)
54  {
55      // 處理超時邏輯;
56  }
57  
58  if(0 != pConnectOptions->nErrNum)
59  {
60      // 處理錯誤連接邏輯
61  }
62  
63  // 處理 pConnectOptions 指針;

   可以解決連接超時問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM