postgresql PG::TRDeadlockDetected: 错误: 检测到死锁
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24385407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PG::TRDeadlockDetected: ERROR: deadlock detected
提问by Railsana
I am restarting 8 puma workers via bundle exec pumactl -F config/puma.rb phased-restart
what works fine. Now I am getting more and more postgres errors:
我正在通过bundle exec pumactl -F config/puma.rb phased-restart
正常工作的方式重新启动 8 名 puma 工人。现在我收到越来越多的 postgres 错误:
PG::TRDeadlockDetected: ERROR: deadlock detected
I found a about 50 of idle postgres processes running:
我发现大约有 50 个空闲的 postgres 进程在运行:
postgres: myapp myapp_production 127.0.0.1(59950) idle
postgres: myapp myapp_production 127.0.0.1(60141) idle
...
They disappear when I am running bundle exec pumactl -F config/puma.rb stop
.
After starting the app with bundle exec pumactl -F config/puma.rb start
, I get exactly 16 idle processes. (Eight too many in my opinion.)
当我跑步时它们消失了bundle exec pumactl -F config/puma.rb stop
。使用 启动应用程序后bundle exec pumactl -F config/puma.rb start
,我正好得到 16 个空闲进程。(我认为八个太多了。)
How can I manage these processes better? Thanks for your help!
如何更好地管理这些流程?谢谢你的帮助!
Update
更新
My puma.rb:
我的 puma.rb:
environment 'production'
daemonize true
pidfile 'tmp/pids/puma.pid'
state_path 'tmp/pids/puma.state'
threads 0, 1
bind 'tcp://0.0.0.0:3010'
workers 8
quiet
回答by Railsana
I might have found a solution to my question:I had some queries outside of my controllers (custom middleware), which seem to have caused the problem.
我可能已经找到了我的问题的解决方案:我在控制器(自定义中间件)之外进行了一些查询,这似乎导致了问题。
If you have queries outside of controllers (ActiveMailer could also cause this problem), put your code in a ActiveRecord::Base.connection_pool.with_connection
block:
如果您在控制器之外有查询(ActiveMailer 也可能导致此问题),请将您的代码放在一个ActiveRecord::Base.connection_pool.with_connection
块中:
ActiveRecord::Base.connection_pool.with_connection do
# code
end
ActiveRecord's with_connection method yields a database connection from its pool to the block. When the block finishes, the connection is automatically checked back into the pool, avoiding connection leaks.
ActiveRecord 的 with_connection 方法产生一个从它的池到块的数据库连接。当块完成时,连接会自动检回到池中,避免连接泄漏。
I hope this helps some of you!
我希望这对你们中的一些人有所帮助!
回答by getabetterpic
Looks like this may be due to the database connections not getting closed on server shutdown. https://github.com/puma/puma/issues/59A lot of people in that issue are using ActiveRecord:: ConnectionAdapters::ConnectionManagement to handle this, or you may be able to roll your own by using Puma's on_restarthook.
看起来这可能是由于数据库连接在服务器关闭时没有关闭。https://github.com/puma/puma/issues/59该问题中的很多人都在使用 ActiveRecord::ConnectionAdapters::ConnectionManagement 来处理这个问题,或者您可以使用 Puma 的on_restart钩子来推出自己的。