新手问题 从 ConnectionPool 中获取的 connection 什么时候会放回 Pool?

Dounx · 2020年01月02日 · 最后由 Dounx 回复于 2020年01月03日 · 2234 次阅读

在 database.yml 中配置:

pool: 5 

有 10 个线程,执行以下代码:

author = Author.first

sql = 'some find sql'
result = Person.connection.execute(sql)

前 5 个线程都会正常执行,到第 6 个线程的时候,需要等待 5s 之后才能获取到 connection。

  1. 当一个线程在运行结束的时候是否需要调用 ActiveRecord::Base.clear_active_connections! 方法?
  2. ActiveRecord::Base.connection.execute 之类的链式调用会自动释放数据库连接吗?
  3. Rails 中何时会释放 connection?是由 ActiveRecord 负责吗?

参考链接:

  1. https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html
  2. https://bibwild.wordpress.com/2014/07/17/activerecord-concurrency-in-rails4-avoid-leaked-connections/
需要 登录 后方可回复, 如果你还没有账号请 注册新账号