gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:14:43 27 4
gpt4 key购买 nike

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

我听说大多数其他应用程序会为每个工作单元打开一个连接。例如,在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com