登录
首页 >  Golang >  Go问答

如何设置 golang MySQL 驱动程序的 ping 超时时间为 2 秒?

来源:stackoverflow

时间:2024-03-29 14:03:31 367浏览 收藏

哈喽!今天心血来潮给大家带来了《如何设置 golang MySQL 驱动程序的 ping 超时时间为 2 秒?》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我在弄清楚如何在 go 中正确设置数据库连接尝试超时时遇到一些麻烦。我使用这个优秀资源中的一些示例作为基础。我相信我已经正确设置了所有内容,但我的 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。


解决方案


可能是这个问题:https://github.com/golang/go/issues/27476

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

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

本篇关于《如何设置 golang MySQL 驱动程序的 ping 超时时间为 2 秒?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>