golang 语言,在打开mysql DB时,有时会用到timeout,readTimeout两个参数。

建立连接超时时间

例如, "30s", "0.5m" or "1m30s".

2.readTimeout

I/O读超时时间

例如, "30s", "0.5m" or "1m30s".

2.1 底层实现原理

2.1.1 readTimeout的初始化

所在文件:go-sql-driver/mysql/driver.go

// Open new Connection.
// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how
// the DSN string is formated
func (d MySQLDriver) Open(dsn string) (driver.Conn, error) {
.....
	// Set I/O timeouts
	mc.buf.timeout = mc.cfg.ReadTimeout
	mc.writeTimeout = mc.cfg.WriteTimeout
....

将配置的timeout赋值到结构体中。

2.1.2 readTimeout的使用

文件:go-sql-driver/mysql/buffer.go
代码:

// fill reads into the buffer until at least _need_ bytes are in it
func (b *buffer) fill(need int) error {

....
		if b.timeout > 0 {
			if err := b.nc.SetReadDeadline(time.Now().Add(b.timeout)); err != nil {
				return err
			}
		}
....

从上面代码可以看到,通过调用SetReadDeadline()设置读的最大时间。
每次读消耗的最大时间不超过设置的时间。

3.参考

golang mysql driver

相关文章:

  • 2021-05-27
  • 2021-09-30
  • 2021-10-31
  • 2021-11-27
  • 2021-12-30
  • 2021-09-28
猜你喜欢
  • 2021-11-18
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-03
  • 2021-04-19
相关资源
相似解决方案