ruby-on-rails - 有什么理由在 ActiveRecord 中使用数据库连接池吗?

标签 ruby-on-rails postgresql activerecord connection-pooling

使用外部连接池有什么好处?

我听说大多数其他应用程序会为每个工作单元打开一个连接。例如,在 Rails 中,我认为这意味着每个请求都可以打开一个新连接。我假设连接池将使这成为可能。

我能想到的唯一好处是,它允许您拥有 1,000 个前端进程,而无需运行 1,000 个 postgres 进程。

还有其他好处吗?

最佳答案

Rails 有 connection pooling built in :

  1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and earlier (pre-connection-pooling). Eventually, when you’re done with the connection(s) and wish it to be returned to the pool, you call ActiveRecord::Base.clear_active_connections!. This will be the default behavior for Active Record when used in conjunction with Action Pack’s request handling cycle.
  2. Manually check out a connection from the pool with ActiveRecord::Base.connection_pool.checkout. You are responsible for returning this connection to the pool when finished by calling ActiveRecord::Base.connection_pool.checkin(connection).
  3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which obtains a connection, yields it as the sole argument to the block, and returns it to the pool after the block completes.

这已经可用since version 2.2 .您将在 database.yml 中看到一个用于控制它的 pool 参数:

pool: number indicating size of connection pool (default 5)

我认为在其下层叠另一个池化系统没有多大意义,如果您尝试这样做,它甚至可能会混淆 AR 的池化。

关于ruby-on-rails - 有什么理由在 ActiveRecord 中使用数据库连接池吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5826381/

相关文章:

ruby-on-rails - 如何在 Rails 中获取 URL 参数?

ruby-on-rails - RoR : How to get an empty/new line in a plain text email

postgresql - 如何将 pandas DataFrame 插入现有的 PostgreSQL 表?

postgresql - pg_restore 会覆盖现有表吗?

javascript - 使用嵌套形式初始化对象不起作用

ruby-on-rails - 检索 AR 模型的所有关联属性?

ruby-on-rails - Rails : how should I share logic between controllers?

PostgreSQL: block 中的页眉无效

php - 限制不适用于 ActiveRecord

ruby-on-rails - 在 Ruby on Rails 中使用个人资料图片