【问题标题】:ActiveRecord leaks connections when using in Rack middleware在 Rack 中间件中使用时 ActiveRecord 泄漏连接
【发布时间】:2013-06-25 17:17:19
【问题描述】:

对于数据库密集型视图,我已转向数据库非规范化/缓存,以减少服务器资源需求并提高用户性能。视图是由许多不同表中的数据组成的摘要视图,因此许多不同的数据更改也会更新缓存。

为了减少缓存中的流失,我求助于 Rack 中间件。我的中间件如下所示:

class MyMiddleware
  def initialize(app)
    @app = app
  end
  def call(env)
    # ... prepare in memory storage for what needs to change
    return_value = @app.call(env)
    # ... commit changes to the database
    return_value
  end
end

在应用加载一段时间之前,一切看起来都很棒。然后我开始在日志中偶尔看到以下错误:

Status: 500 Internal Server Error
could not obtain a database connection within 5 seconds.  The max pool size is currently 5; consider increasing it.

当我删除中间件后,应用程序又可以正常工作了。

使用 Rack 中间件的 ActiveRecord 时如何修复连接泄漏?

【问题讨论】:

    标签: ruby-on-rails activerecord connection-pooling rack


    【解决方案1】:

    ActiveRecord 提供了一种手动清除连接的方法 - ActiveRecord::Base.clear_active_connections!。更新中间件中的call方法,在数据库发生更改后清除活动连接。

    def call(env)
      # ... prepare in memory storage for what needs to change
      return_value = @app.call(env)
      # ... commit changes to the database
      ActiveRecord::Base.clear_active_connections! # fixes the connection leak
      return_value
    end
    

    http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 2019-12-04
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多