gpt4 book ai didi

ruby-on-rails - 替换 ActiveRecord 5 中的 ActiveRecord::ConnectionAdapters::ConnectionManagement

转载 作者:数据小太阳 更新时间:2023-10-29 06:41:41 26 4
gpt4 key购买 nike

我们正在升级 Sinatra来自ActiveRecord 4的申请到 ActiveRecord 5。以前我们有这一行:

使用 ActiveRecord::ConnectionAdapters::ConnectionManagement

这是因为连接在请求完成后没有被清理。这是关于此主题的先前 SO 讨论:

从 ActiveRecord 5 开始,这条线不再有效。这conversation in the rails project states :

This was removed in favor of Executor and Reloader APIs. That middleware that was removed were not part of the public API. If you want to use that outside Rails you need to make one.

这是否意味着,如果有人要将 ActiveRecord 5 与 Sinatra 一起使用,除非开发人员重新创建现在已删除的中间件,否则连接将在请求后再次“泄漏”或未返回到池中?

在 Sinatra 示例中,是否因此需要在 ActiveRecord 5 中包含这一行?

after do
ActiveRecord::Base.clear_active_connections!
end

这是链接到线程的含义,但我想得到一个明确的答案,我可以带回我的开发团队。

最佳答案

你是对的,ConnectionManagement 中间件已从 ActiveRecord 5 (PR #23807) 中删除,因此在 Rails 之外设置 ActiveRecord 时需要复制类似的功能。有几种方法可以做到这一点:

1。 ConnectionManagement 机架中间件

ConnectionManagement class不是很复杂。您可以将实现复制并粘贴到本地应用程序的某处,并像往常一样将其包含到您的 Rack 中间件堆栈中:

class ConnectionManagement
def initialize(app)
@app = app
end

def call(env)
testing = env['rack.test']

status, headers, body = @app.call(env)
proxy = ::Rack::BodyProxy.new(body) do
ActiveRecord::Base.clear_active_connections! unless testing
end
[status, headers, proxy]
rescue Exception
ActiveRecord::Base.clear_active_connections! unless testing
raise
end
end

use ConnectionManagement

2。 (Sinatra 特定的)连接管理 after hook

在 Sinatra 应用程序中,您建议的 block 应该有效:

after do
ActiveRecord::Base.clear_active_connections!
end

注意这也是方法currently used通过sinatra-activerecord集成 gem 以支持 ActiveRecord 5(请参阅问题 #73)。

3。 ActionDispatch::Executor 机架中间件

最后,您可以使用 Rails 现在用于 ActiveRecord 连接管理的相同代码,方法是将 ActionDispatch::Executor 添加到您的 Rack 中间件堆栈,并调用 ActiveRecord::QueryCache#install_executor_hooks插入用于清除 ActiveRecord 连接的 Hook :

require 'action_dispatch/middleware/executor'
use ActionDispatch::Executor, ActiveSupport::Executor
ActiveRecord::QueryCache.install_executor_hooks

关于ruby-on-rails - 替换 ActiveRecord 5 中的 ActiveRecord::ConnectionAdapters::ConnectionManagement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41400202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com