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

Dounx · January 02, 2020 · Last by Dounx replied at January 03, 2020 · 2235 hits

在 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/
You need to Sign in before reply, if you don't have an account, please Sign up first.