使用外部连接池有什么好处?
我听说大多数其他应用程序会为每个工作单元打开一个连接。例如,在 Rails 中,我认为这意味着每个请求都可以打开一个新连接。我假设连接池将使这成为可能。
我能想到的唯一好处是,它允许您拥有 1,000 个前端进程,而无需运行 1,000 个 postgres 进程。
还有其他好处吗?
最佳答案
Rails 有 connection pooling built in :
- 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.
- 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).
- 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/