Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord在使用机架内中间件时泄漏连接_Ruby On Rails_Activerecord_Connection Pooling_Rack - Fatal编程技术网

Ruby on rails ActiveRecord在使用机架内中间件时泄漏连接

Ruby on rails ActiveRecord在使用机架内中间件时泄漏连接,ruby-on-rails,activerecord,connection-pooling,rack,Ruby On Rails,Activerecord,Connection Pooling,Rack,对于数据库密集型视图,我转向了数据库非规范化/缓存,以减少服务器资源需求并提高用户性能。该视图是由许多不同表中的数据组成的摘要视图,因此许多不同的数据更改也会更新缓存 为了减少缓存中的搅动,我转向机架中间件。我的中间件如下所示: class MyMiddleware def initialize(app) @app = app end def call(env) # ... prepare in memory storage for what needs to cha

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

为了减少缓存中的搅动,我转向机架中间件。我的中间件如下所示:

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.
当我移除中间件时,应用程序再次正常工作


从机架中间件使用ActiveRecord时,如何修复连接泄漏?

ActiveRecord提供了手动清除连接的方法-
ActiveRecord::Base.clear\u active\u 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