8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SQLAlchemy で Lost connection を抑止

Last updated at Posted at 2019-06-19

ググると古い情報しか出ないのでメモ。Dealing with Disconnects に対策が書いてある。

SQLAlchemy の create_engine で作った Engine は標準で Connection Pool が有効なので、DB 接続を使い回すようなっている。ただ、このままだと再利用しようと思った接続が勝手に切れていたり、DB が再起動した場合に次回 SQL を発行した時に Lost connection エラーになる事がある。例えば長時間アクセスしなかった DB にアクセスすると、エラーが発生する。この抑止方法として二つの方法が紹介されている。

  • 悲観的な切断検出は、DB 接続を利用する前にかならず "SELECT 1" などの簡単な SQL を発行して接続を確認する。実装方法は create_enginepool_pre_ping 引数を渡すだけなので簡単だが、ちょっとオーバーヘッドがある。
  • 楽観的な切断検出は、DB に接続する時にエラーが出たら一度だけリトライを行う(?)というもの。SQLAlchemy は切断を検知すると自動的に再接続を行う。という事だと思うけど、いまいちコードサンプルの意図が分からず自信が無い。
8
8
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
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?