LoginSignup
21
9

More than 5 years have passed since last update.

Railsでマルチスレッドを使う時はDB_Connectionの最大数に注意

Posted at

危険な書き方

Thread.new do
   puts "#{User.find(1).id}"
end

上記の様にThred.newの中でDB接続を行っている場合、スレッド毎にDBコネクションが作成されてしまう。
database.ymlのconnection_pool数(デフォルトは5)を超えると以下の様なエラーが発生します。

could not obtain a connection from the pool within 5.000 seconds (waited 5.000 seconds); 
all pooled connections were in use (ActiveRecord::ConnectionTimeoutError)

解決策

マルチスレッド内でDBアクセスする場合にDBコネクションを使い回す様に書き直す。

Thread.new do
-  puts "#{User.find(1).id}"
+  ActiveRecord::Base.connection_pool.with_connection do
+    puts "#{User.find(1).id}"
+  end
end

参考

http://shirusu-ni-tarazu.hatenablog.jp/entry/2013/07/02/042448
https://easyramble.com/activerecord-with-multi-threads.html

21
9
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
21
9