iis服务器助手广告
返回顶部
首页 > 资讯 > 后端开发 > GO >如何设置 golang MySQL 驱动程序的 ping 超时时间为 2 秒?
  • 494
分享到

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

2024-04-05 00:04:29 494人浏览 八月长安
摘要

哈喽!今天心血来潮给大家带来了《如何设置 golang Mysql 驱动程序的 ping 超时时间为 2 秒?》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到

哈喽!今天心血来潮给大家带来了《如何设置 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的相关知识,请关注编程网公众号!

您可能感兴趣的文档:

--结束END--

本文标题: 如何设置 golang MySQL 驱动程序的 ping 超时时间为 2 秒?

本文链接: https://www.lsjlt.com/news/595923.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作