Mysql網路斷開重連問題,mysql網路斷開

來源:互聯網
上載者:User

Mysql網路斷開重連問題,mysql網路斷開

最近做一個項目的後台精靈,需要多線程對mysql資料庫服務進行操作,為了加強守護撐的健壯性,特地串連成功後拔掉網線,然後測試精靈斷開重新串連的健壯性,可是發現網路斷開後,重新插上網線,用mysql_real_conncet進行重新串連返回的永遠是假,也就是重新串連失敗,之後我想斷開網路後重新將mysql串連釋放(mysql_close(MYSQL )),並重新初始化mysql_init((MYSQL )),然後再用mysql_real_conncet()函數進行串連,但是這樣做的後果是mysql_real_connect()報錯,報錯內容為沒有足夠的記憶體,明明我的電腦還有5個G空閑記憶體,居然說記憶體不夠。。。
經過查閱資料,發現有一個叫mysql_options的函數,結合mysql_ping函數,mysql串連斷開後可以自動重新串連:
使用mysql_ping來自動檢查重連。用到兩個函數,一個是mysql_ping,另外一個是mysql_options。具體使用方法是在mysql_real_connect之前,mysql_init之後,使用mysql_options。用法如下:

 char value = 1; (void) mysql_init (&mysql); mysql_options(&mysql, MYSQL_OPT_RECONNECT, (char *)&value);

結合百度百科的使用方法:
mysql_optins
mysql_ping


然後在以後mysql_query之前首先使用mysql_ping進行判斷,如果串連已經斷開,會自動重連,或者再查詢失敗後,執行mysql_ping函數,然後自動重新串連mysqlsever.
不過,請注意,自動重新串連也會導致一些副作用,如下:
* 任何活動的交易都被復原,autocommit模式被置為reset。
* 所有表鎖都釋放
* 所有暫存資料表是關閉(撤消)
* Session variables are reinitialized to the values of the corresponding variables.會話變數被重新初始化為相應的變數。 這也影響那些隱式聲明的變數,SET NAMES。比如使用This also affects variables that are set implicitly by statements such as SET NAMES.這也影響了變數,是一套由含蓄的聲明,例如訂定的名稱。
* 使用者變數設定都將丟失。
* 編製報表釋放。
* 控制代碼變數被關閉。
* LAST_INSERT_ID()被重設為0 。
* 使用GET_LOCK()獲得的鎖被釋放

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.