是否有理由将数据库连接池与 ActiveRecord 一起使用?

发布于 2024-11-04 04:11:05 字数 187 浏览 1 评论 0原文

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

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

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

还有其他好处吗?

What are the benefits to using an external connection pool?

I've heard that most other applications will open up a connection for each unit of work. In Rails, for example, I'd take that to mean that each request could open a new connection. I'm assuming a connection pool would make that possible.

The only benefit I can think of is that it allows you to have 1,000 frontend processes without having 1,000 postgres processes running.

Are there any other benefits?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

意中人 2024-11-11 04:11:05

Rails 具有内置连接池

  1. 只需使用 ActiveRecord::Base.connection 即可,就像 Active Record 2.1 及更早版本(预连接池)一样。最终,当您完成连接并希望将其返回到池中时,您可以调用 ActiveRecord::Base.clear_active_connections!。当与 Action Pack 的请求处理周期结合使用时,这将是 Active Record 的默认行为。
  2. 使用 ActiveRecord::Base.connection_pool.checkout 从池中手动检出连接。您负责在完成后通过调用 ActiveRecord::Base.connection_pool.checkin(connection) 将此连接返回到池中。
  3. 使用 ActiveRecord::Base.connection_pool.with_connection(&block),它会获取一个连接,将其作为块的唯一参数,并在块完成后将其返回到池中。

自版本 2.2 起可用。您将在 database.yml 中看到一个 pool 参数来控制它:

pool:表示连接池大小的数字(默认5)

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

Rails has 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.

This has been available since version 2.2. You'll see a pool parameter in your database.yml for controlling it:

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

I don't think there would be much point in layering another pooling system underneath it and it could even confuse AR's pooling if you tried it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文