dongyuan9149 2016-11-10 12:36
浏览 198

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

When I connect to database (using standard go sql library) using VPN and VPN interface goes down, there's a 75 seconds timeout when I try to do SQL query, no matter if the interface goes up meanwhile. I'd like to decrease this timeout to some reasonable time, so my application won't be frozen for 75 seconds in such case.

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

Is it possible to set it somehow via db variable?

  • 写回答

3条回答 默认 最新

  • duanmei1922 2017-07-08 19:37
    关注

    Starting with Go 1.8, the sql.DB abstraction now accepts context.Context, which can be used to time out connections faster.

    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
    }
    

    If your DoLookup function doesn't yet take a context.Context (and it really should!) you can create a parent one by calling context.TODO().

    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了