在 Go 中为 SQL 连接设置 TCP 超时

当我使用 VPN 连接到数据库(使用标准 go sql 库)并且 VPN 接口关闭时,无论接口是否同时启动,当我尝试执行 SQL 查询时都会超时 75 秒。我想将此超时减少到某个合理的时间,因此在这种情况下,我的应用程序不会冻结 75 秒。

db, err := sql.Open(driverName, dataSourceName)

是否可以通过db变量以某种方式设置它?


天涯尽头无女友
浏览 253回答 2
2回答

jeck猫

该database/sql包没有提供一种通用的方法来超时调用database/sql.Open. 但是,各个驱动程序通过 DSN (dataSourceName) 连接字符串提供此功能。https://github.com/lib/pqsql.Open("postgres", "user=user dbname=dbname connect_timeout=5")https://github.com/go-sql-driver/mysqlsql.Open("mysql", "user:password@/dbname?timeout=5s")https://github.com/denisenkom/go-mssqldbsql.Open("sqlserver", "sqlserver://username:password@host/instance?dial+timeout=5")ETC ...

守着一只汪

从 Go 1.8 开始,sql.DB抽象现在接受context.Context,可用于更快地超时连接。func (c *Client) DoLookup(ctx context.Context, id int) (string, error) {  var name string  // create a child context with a timeout  newCtx, cancel := context.WithTimeout(ctx, time.Second)  // release resources used in `newCtx` if  // the DB operation finishes faster than the timeout  defer cancel()  row := c.db.QueryRowContext(newCtx, "SELECT name FROM items WHERE id = ?", id)  err := row.Scan(&name)  if err != nil {    return "", err  }  return name, nil}如果你的DoLookup函数还没有使用context.Context(它真的应该!)你可以通过调用来创建一个父函数context.TODO()。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go