LoginSignup
3
3

More than 5 years have passed since last update.

postgresqlでのconnection timeout

Posted at

症状

pgpool-IIをネットワークインターフェースごと落とした際に、connect_timeoutを設定していても
初回のクエリ実行でのみtimeoutがエラーが返ってこないという現象にあたったのでそれの対処方法
https://godoc.org/github.com/lib/pq

症状が出た時の環境

  • golang: 1.7系
  • ドライバ: lib/pq
  • pgpool-II: 3.6.1
  • PostgreSQL: 9.5

対処方法

golangを1.8にバージョンアップしてQueryRowContextを使う
https://golang.org/pkg/database/sql/#DB.QueryRowContext

QueryRow以外にもContext版があるのでそちらを使う

//前の処理
//Timeout Contextを作成
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

errChan := make(chan error, 1)

query := "select name from user limit 1"
var name string

go func() {
 errChan <- db.QueryRowContext(ctx, query).Scan(&name)
}()

select {
case <-ctx.Done():
    err = ctx.Err()
    break
case err = <-errChan:
    break
}
//続きの処理
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3