在 Puma 中,我如何计算数据库连接?

In Puma, how do I calculate DB connections?

我正在尝试计算我的应用程序将使用多少个数据库连接。

它是 Rails 5 托管在 Heroku 上。

这是我的 Puma 配置

workers Integer(ENV['WEB_CONCURRENCY'] || 2)
threads_count = Integer(ENV['RAILS_MAX_THREADS'] || 5)
threads threads_count, threads_count

preload_app!

rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

on_worker_boot do
  ActiveRecord::Base.establish_connection
end

我的数据库配置的第一部分:

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV['RAILS_MAX_THREADS'] || 5 %>

我觉得奇怪的部分是连接数,而且我在 database.yml 中的 pool 设置都使用 RAILS_MAX_THREADS... 但它不应该使用RAILS_MAX_THREADS 乘以工人数 (WEB_CONCURRENCY?

其实我发现这里的答案解释得很好... https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#database-connections


随着您向应用程序添加更多的并发性,它将需要更多的数据库连接。确定每个应用程序需要的连接数的一个很好的公式是 RAILS_MAX_THREADS 乘以 WEB_CONCURRENCY。这种组合将决定每个 dyno 将消耗的连接数。

Rails 维护其数据库连接池,为每个工作进程创建一个新池。 worker 中的线程将在同一个池中运行。确保 Rails 数据库连接池中有足够的连接,以便可以使用 RAILS_MAX_THREADS 个连接。如果您看到此错误:

ActiveRecord::ConnectionTimeoutError - could not obtain a database connection within 5 seconds

此错误表明您的 Rails 连接池太低。要深入了解这些主题,请阅读开发中心文章 Concurrency and Database Connections