对于数据库密集型视图,我转向了数据库非规范化/缓存,以减少服务器资源需求并提高用户性能。该视图是由许多不同表中的数据组成的摘要视图,因此许多不同的数据更改也会更新缓存。
为了减少缓存中的流失,我转向了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.
当我移除中间件时,应用程序将重新正常工作。
使用机架中间件的ActiveRecord时,如何修复连接泄漏?
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