#...
app = Rack::Builder.app do
use ActiveRecord::ConnectionAdapters::ConnectionManagement
end
run app
#...
require_relative 'config/environment'
app = Rack::Builder.app do
run Resources::Index
end
# 处理连接的配置
exe = ActiveSupport::Executor
ActiveRecord::QueryCache.install_executor_hooks(exe)
run lambda { |env| exe.wrap { app.call(env) } }
# 其他需要加载/初始化的动作
# 下面这几行很关键,因为在非 Rails 应用中,启动时不会自动初始化 `connection_handlers`,然而 ActiveRecord::QueryCache 中有
# 使用到了,对于 Rails 中的 `connection_management_test.rb` 之所以能跑通,是因为在 `activerecord/test/cases/helper.rb` 中调
# 用了 `ARTest.connect`,而这个方法里面明确的初始化了 `connection_handlers`
ActiveRecord::Base.class_eval do
self.connection_handlers = { writing_role => default_connection_handler }
end
#...
app = Rack::Builder.app do
use OTR::ActiveRecord::ConnectionManagement
end
run app
没有尝试
假如每次请求返回都是 false,表示清理成功了
# config.ru
class TestConnectionManagement
def initialize(app)
@app = app
end
def call(env)
puts ActiveRecord::Base.connection_handler.active_connections?
@app.call(env)
end
end
app = Rack::Builder.app do
use TestConnectionManagement
# ...
end
# ...
我是用 Rails 6 测试的,但是 ActiveRecord::ConnectionAdapters::ConnectionManagement
在 Rails 5 就移除了,所以使用方式可能有些差异,比如可能 Rails5 中不需要自己去初始化 connection_handlers
,源码没去细看了,如果用 Rails 5 的可以先试着不初始化 connection_handlers
,看看结果怎么样。
https://github.com/jhollinger/otr-activerecord
https://stackoverflow.com/questions/41400202/replacing-activerecordconnectionadaptersconnectionmanagement-in-activerecord
https://github.com/jhollinger/otr-activerecord