fix(db): 处理MySQL连接的只读副本错误

在连接MySQL时,增加对只读副本可能返回的错误(8001和polar slave)的处理逻辑,确保连接在出现此类错误时仍然可用。
This commit is contained in:
zhouyonggao 2025-12-08 11:31:28 +08:00
parent 3efd6e0e60
commit 02cd5f75b9
2 changed files with 11 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package db
import (
"database/sql"
"strings"
_ "github.com/go-sql-driver/mysql"
)
@ -12,6 +13,16 @@ func ConnectMySQL(dsn string) (*sql.DB, error) {
return nil, err
}
if err := db.Ping(); err != nil {
// Error 8001: Not allowed to execute statement that may change data on polar slave
// This error can occur on read-only replicas but the connection may still be usable
// Try a simple SELECT to verify the connection is actually working
if strings.Contains(err.Error(), "8001") || strings.Contains(err.Error(), "polar slave") {
var dummy int
if testErr := db.QueryRow("SELECT 1").Scan(&dummy); testErr == nil {
// Connection is actually working, ignore the ping error
return db, nil
}
}
return nil, err
}
return db, nil

Binary file not shown.