1. 程式人生 > >golang database sql DSN (Data Source Name)中的timeout, readTimeout

golang database sql DSN (Data Source Name)中的timeout, readTimeout

golang 語言,在開啟mysql DB時,有時會用到timeout,readTimeout兩個引數。

1.timeout

建立連線超時時間

例如, "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