【问题标题】:How can I get golang mysql driver to timeout pings in 2 seconds?如何让 golang mysql 驱动程序在 2 秒内超时 ping?
【发布时间】: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。

【问题讨论】:

标签: mysql go timeout connection-timeout


【解决方案1】:

会不会是这个问题:https://github.com/golang/go/issues/27476

我的问题略有不同,它会超时一个 1s 而不是 2s 或 3s! https://media.dev.unee-t.com/2018-09-05/pingcontext.mp4

我的来源在这里:https://media.dev.unee-t.com/2018-09-05/main.go

【讨论】:

  • 是的!事实上,这就是我与这个问题同时制作的错误报告,让他们知道这个问题哈哈。一旦那里有解决方案,我们也应该知道这里的解决方案。很高兴了解 1s 解决方法,谢谢!
【解决方案2】:

我使用下面的 MySQL DSN 格式在 2s 内超时,效果很好。

user:password@tcp(localhost:80)/dbname?timeout=2s

【讨论】:

    猜你喜欢
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 2011-02-07
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多