read_timeout 參數:修改 C 擴充原始碼並重新編譯安裝MySQLdb(_mysql C 擴充)預設不支援 MYSQL_OPT_READ_TIMEOUT,導致查詢阻塞時無法自動超時,影響高可用架構下的自動切換。本文示範修改 _mysql.c、setup_posix.py 並重新編譯安裝,賦予 connect() 原生 read_timeout 參數。
connect_timeout 僅管連線階段,read_timeout 管查詢階段,兩者缺一不可。_mysql.c(關鍵差異)
diff --git a/_mysql.c b/_mysql.c
index d42cc54..61a9b34 100644
--- a/_mysql.c
+++ b/_mysql.c
@@ -489,9 +489,10 @@ _mysql_ConnectionObject_Initialize(
"named_pipe", "init_command", "read_default_file",
"read_default_group", "client_flag", "ssl",
- "local_infile",
+ "local_infile", "read_timeout",
NULL };
int connect_timeout = 0;
+int read_timeout = 0;
@@ -500,7 +501,7 @@ _mysql_ConnectionObject_Initialize(
self->converter = NULL;
self->open = 0;
check_server_init(-1);
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ssssisOiiisssiOi:connect",
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ssssisOiiisssiOii:connect",
kwlist,
@@ -509,7 +510,8 @@ _mysql_ConnectionObject_Initialize(
&init_command, &read_default_file, &read_default_group,
&client_flag, &ssl,
- &local_infile /* DO NOT PATCH FOR RECONNECT, IDIOTS */
+ &local_infile, &read_timeout
+ /* DO NOT PATCH FOR RECONNECT, IDIOTS IF YOU DO THIS, I WILL NOT SUPPORT YOUR PACKAGES. */
)) return -1;
@@ -540,6 +542,12 @@ _mysql_ConnectionObject_Initialize(
mysql_options(&(self->connection), MYSQL_OPT_CONNECT_TIMEOUT, (char *)&timeout);
}
+if (read_timeout) {
+ unsigned int timeout = read_timeout;
+ mysql_options(&(self->connection), MYSQL_OPT_READ_TIMEOUT, (char *)&timeout);
+}
+
if (compress != -1) {
mysql_options(&(self->connection), MYSQL_OPT_COMPRESS, 0);
setup_posix.py 找不到 mysql_config
diff --git a/setup_posix.py b/setup_posix.py
index 86432f5..f4f08f1 100644
--- a/setup_posix.py
+++ b/setup_posix.py
@@ -23,7 +23,7 @@ def mysql_config(what):
if ret/256 > 1:
raise EnvironmentError("%s not found" % (mysql_config.path,))
return data
-mysql_config.path = "mysql_config"
+mysql_config.path = "/usr/local/mysql/bin/mysql_config"
python setup.py install
# 測試
import MySQLdb
conn = MySQLdb.connect(host=DB_SERVER, user=DB_USER, passwd=DB_PASS,
db=DB_NAME, port=int(DB_PORT),
client_flag=2, read_timeout=10)
cursor = conn.cursor()
cursor.execute("SELECT SLEEP(15)") # 10 秒後拋 OperationalError (2013)
OperationalError: (2013, 'Lost connection to MySQL server during query')
查詢超時 10 秒自動中斷,應用層可捕獲異常並觸發重試/切換邏輯。
read_timeout、write_timeout,API 與 MySQLdb 高度相容,建議新專案直接採用。read_timeout 支援(pip install mysqlclient)。若受限於舊專案必須用 MySQLdb,本文修改方案經實測穩定;長期建議遷移至 PyMySQL 或 mysqlclient 享受原生支援與持續維護。