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