ruby mysql 连接池,为单线程Rails应用程序正确设置数据库连接池database.yml

博客讨论了Rails默认数据库连接池设置为5的原因。尽管Rails 3默认是单线程的,但考虑到可能使用如Sidekiq等多线程后台任务处理库,多个连接是必要的,以确保在并发操作时有足够的资源。特别是当任务可能会超过默认的5秒数据库连接超时时,更大的连接池可以避免错误并保持应用的稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I was wondering about the following setting in the Rails database.yml:

By default the number of database connections for the connection pool of ActiveRecord is set to 5:

development:

...

pool: 5

But by default, Rails 3 is single threaded.

Why would you need 5 connections by default?

As far as I understand, a single threaded Rails app can't trigger multiple database operations at once, why would do you need to keep more connection open?

I would assume that 2 connections would make sense, so you always have one active connection even if the other one times out, but holding five connections seems a little odd to me.

Am I missing something?

In fact these default settings don't make any sense, it was fixed but then temporarily reverted (one year ago) because of the test suite.

解决方案

Quite late to the party here, but I ran out of database connections today in production.

Like a lot of people, I use Sidekiq to perform asynchronous jobs like sending emails for example. It is important to note that Sidekiq runs as a multithread process.

So, I don't just have a single-threaded Rails application, therefore this answer does not directly apply to the question asked but I thought it was worth saying something here as I think multithreaded Rails apps are relatively normal nowadays.

This means you need to adjust your pool size in such a way as to create enough connections to handle all the jobs that can be enqueued and take longer than 5 seconds (the default timeout period to wait for a database connection before throwing an error).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值