1. 程式人生 > >MYSQL 的重新連線錯誤:MySQL server has gone away

MYSQL 的重新連線錯誤:MySQL server has gone away

轉自:http://blog.csdn.net/qq7183316/article/details/9156991

之所以寫那篇blog,是因為去年寫的一些程式碼遇到了“2006:MySQL server has gone away”錯誤。這個問題是因為wait_timeout這個引數的預設值是28800,也就是說,如果一個連線連續8個小時沒有任何請求,那麼Server端就會把它斷開。在測試環境中一個晚上沒有請求很正常……於是第二天早上來的時候就發現這個錯誤了。


其實我有考慮這個問題的,真的……因為我知道php裡面有個函式叫做mysql_ping(),PHP手冊上說:“mysql_ping() 檢查到伺服器的連線是否正常。如果斷開,則自動嘗試連線。本函式可用於空閒很久的指令碼來檢查伺服器是否關閉了連線,如果有必要則重新連線上。”

回想起來,以前真是很傻很天真。根據MySQL官方C API裡
mysql_ping()的文件
:"Checks whether the connection to the server is working. If the connection has gone down and auto-reconnect is enabled an attempt to reconnect is made. ... Auto-reconnect is disabled by default. To enable it, call mysql_options() with the MYSQL_OPT_RECONNECT option",也就是說,它實際上還依賴於MYSQL_OPT_RECONNECT這個配置,而這個配置預設(自5.0.3開始)是關閉的!

雖然想起來很憤怒很蛋疼,不過看到 libmysql/client.c: mysql_init() 裡的註釋就淡定了:
引用 By default we don't reconnect because it could silently corrupt data (after reconnection you potentially lose table locks, user variables, session variables (transactions but they are specifically dealt with in mysql_reconnect()).  This is a change: < 5.0.3 mysql->reconnect was set to 1 by default. 

好吧,既然有問題,那就正視它。解決辦法是呼叫 mysql_options ,將MYSQL_OPT_RECONNECT設定為1:
char
value = 1;
mysql_options(mysql, MYSQL_OPT_RECONNECT, &value);

但是!! 在mysql 5.0.19 之前,mysql->reconnect = 0 這一句是放在 mysql_real_connect() 裡面的!也就是說,如果你不能像處理其他選項一樣,而是必須在mysql_real_connect()之前設定MYSQL_OPT_RECONNECT,坑爹啊!

好吧好吧,總之,關於坑的問題暫告一段落,結論就是,不管是哪個版本,如果你想要啟用自動重連,最好都是在mysql_real_connect()之後,反正不會錯。

然後這篇的重點來了(前面似乎太羅嗦了點):MYSQL_OPT_RECONNECT的文件裡頭說了,這個選項是用來啟用/禁用(當發現連線斷開時的)自動重連,那麼,MYSQL什麼時候會發現連結斷開呢?

這個問題可能太大了,不過不妨先去追一下,mysql_ping()做了啥。

下載原始碼
http://cdn.mysql.com/Downloads/MySQL-5.1/mysql-5.1.67.tar.gz
,解壓以後ctags -R,再vim -t mysql_ping ,馬上就定位到了,似乎太簡單了點: int STDCALL
mysql_ping(MYSQL *mysql)
{
  int res;
  DBUG_ENTER("mysql_ping");
  res= simple_command(mysql,COM_PING,0,0,0);        //試著向伺服器傳送一個ping包
  if (res == CR_SERVER_LOST && mysql->reconnect)    //如果server掛了,而mysql->reconnect為true
    res= simple_command(mysql,COM_PING,0,0,0);      //再ping一次??
  DBUG_RETURN(res);
}

好吧,看來關鍵在於這個simple_command了。ctrl+],原來是這樣:
#define simple_command(mysql, command, arg, length, skip_check) \
  (*(mysql)->methods->advanced_command)(mysql, command, 0, 0, arg, length, skip_check, NULL)

好吧,先去追一下MYSQL,裡頭有個 const struct st_mysql_methods *methods ,再追一下 st_mysql_methods ....
typedef struct st_mysql_methods
{
  my_bool (*read_query_result)(MYSQL *mysql);
  my_bool (*advanced_command)(MYSQL *mysql, enum enum_server_command command,
                  const unsigned char *header, unsigned long header_length,
                  const unsigned char *arg, unsigned long arg_length,
                  my_bool skip_check, MYSQL_STMT *stmt);
  ......
坑爹啊!又是這種鳥程式碼!蛋疼的C語言!struct只有屬性沒有方法!沒辦法,只能暴力了:
引用 find -name '*.c' -exec /bin/grep '{}' -Hne 'mysql->methods *=' ';'
./libmysql_r/client.c:1907:  mysql->methods= &client_methods;
./sql-common/client.c:1907:  mysql->methods= &client_methods;
./libmysql/client.c:1907:  mysql->methods= &client_methods;
./libmysqld/libmysqld.c:120:  mysql->methods= &embedded_methods;
./sql/client.c:1907:  mysql->methods= &client_methods;

果斷追到client_methods: static MYSQL_METHODS client_methods=
{
  cli_read_query_result,                      /* read_query_result */
  cli_advanced_command,                        /* advanced_command */
  ...

也就是說simple_command最後呼叫了cli_advanced_command這個函式。前面的 simple_command(mysql,COM_PING,0,0,0) 相當於是呼叫了 cli_advanced_command(mysql, COM_PING, 0, 0, 0, 0, 0, NULL) 。

這個函式做了啥呢。。。其實也不復雜:
1. 設定預設返回值為1 (意外出錯goto時被返回)
2. 設定sigpipe的handler(以便忽略它)
3. 如果 mysql->net.vio == 0 ,那麼呼叫mysql_reconnect重連,失敗的話就返回1
4. mysql沒準備好,返回1
5. 清除之前的資訊(錯誤碼、緩衝區、affected_rows)等等
6. 呼叫net_write_command將命令傳送給server,如果失敗:
    6.1 檢查錯誤資訊,如果是因為傳送包太大,goto end
    6.2 呼叫end_server(mysql)關閉連線
    6.3 呼叫mysql_reconnect嘗試重連,如果失敗goto end
    6.4 再次呼叫net_write_command將命令傳送給server,失敗則goto end
7. 設定result = 0(傳送成功)
8. 如果引數中要求檢查server的返回,則讀取一個packet進行檢查(失敗的話就result=1)
9. (end標籤)
10. 恢復sigpipe
11. 返回result

可以看到,這裡兩次呼叫了mysql_reconnect,但都是有條件的:第一次是在mysql->net.vio == 0的情況下,第二次是net_write_command失敗且不是因為包太大的情況。vio相關的程式碼看得一頭霧水,實在找不出頭緒,於是決定暴力一點:直接修改這個函式,加入一堆fprintf(stderr, ...)(具體加在哪裡就不說了,反正使勁塞就是了),然後寫了一個C程式碼: #include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>

void do_err(MYSQL *mysql) {
    if (mysql_errno(mysql)) {
        fprintf(stderr, "%d:%s\n", mysql_errno(mysql), mysql_error(mysql));
        exit(mysql_errno(mysql));
    }
}

int main()
{
    MYSQL * mysql = mysql_init(NULL);
    do_err(mysql);

    mysql_real_connect(mysql, "127.0.0.1", "root", "123456", "test", 3306, NULL, 0);
    do_err(mysql);

    char value = 1;
    mysql_options(mysql, MYSQL_OPT_RECONNECT, &value);
   
    char cmd[1024] = "SELECT * FROM t";
    while (1) {
        mysql_query(mysql, cmd);
        do_err(mysql);

        MYSQL_RES *result = mysql_store_result(mysql);

        MYSQL_ROW  row;
        while ((row = mysql_fetch_row(result)) != NULL) {
            int i, num_fields = mysql_num_fields(result);
            for (i = 0; i < num_fields; i++)
                printf("%s\t", row[i] ? row[i] : "NULL");
            //注意上一句是不是二進位制安全的,因為row裡頭可能包含\0,也可能末尾沒有\0
            printf("\n");
        }

        mysql_free_result(result);
        printf("press enter..."); getchar();
    }
    mysql_close(mysql);
    return 0;
}