【发布时间】:2019-02-08 21:21:40
【问题描述】:
我在弄清楚如何在 Go 中正确设置数据库连接尝试超时时遇到了一些麻烦。我使用this excellent resource 的一些示例作为基础。我相信我设置正确,但我的 ping 只是拒绝在 2 秒后超时。我已将相关代码提取到示例程序中,如下所示。请注意,172.1.2.3 上没有运行数据库。
package main
import (
"context"
"database/sql"
_ "github.com/go-sql-driver/mysql" //MySQL driver
"log"
"time"
)
func main() {
log.Print("Trying to ping database!")
//Prepare a "context" to execute queries in, this will allow us to use timeouts
var bgCtx = context.Background()
var ctx2SecondTimeout, cancelFunc2SecondTimeout = context.WithTimeout(bgCtx, time.Second*2)
defer cancelFunc2SecondTimeout()
//Open database connection
db, err := sql.Open("mysql", "root:@tcp(172.1.2.3)/testdb?parseTime=true")
if err != nil {
log.Printf("Unable to open db, %s", err.Error())
return
}
log.Print("Successfully called open()")
//Ping database connection with 2 second timeout
err = db.PingContext(ctx2SecondTimeout)
if err != nil {
log.Printf("Can't ping database server in order to use storage, %s", err.Error())
return
}
log.Print("Successfully pinged database!")
}
运行程序最多需要大约 2 秒,但实际上需要 2 多分钟:
$ go run lambdatry.go
2018/09/03 16:33:33 Trying to ping database!
2018/09/03 16:33:33 Successfully called open()
2018/09/03 16:35:43 Can't ping database server in order to use storage, dial tcp 172.1.2.3:3306: connect: connection timed out
如果我更改“数据库”的 IP(我只是选择了一个随机 IP,因此该地址没有数据库),数据库有时会立即超时,有时需要很长时间才能超时。
我在 ubuntu 18.04 上运行 go 1.10.1。
【问题讨论】:
-
dev.mysql.com/doc/refman/8.0/en/mysql-options.html 和
MYSQL_OPT_READ_TIMEOUT一起玩
标签: mysql go timeout connection-timeout