Rails ActiveRecord establish_connection 不断切换 database config 会有什么恶劣的影响吗?

bobo · 2017年07月13日 · 最后由 bobo 回复于 2017年07月14日 · 2187 次阅读
#model
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

#controller
class HomeController < ApplicationController

    def index
       [:development, :integration, :staging] do |env|
          ApplicationRecord.establish_connection env
       end
    end

end

Question

如果不断访问 home#index,不断切换 db 连接而没有手动释放连接,会对 service 造成什么负担吗?比如说达到一定次数以后连接池爆了?有什么改进方案没。求解惑

如果你是提前建立好了连接,然后直接切换着用,应该没事,每次只是从不同的连接池里拿连接而已。但如果你上边那个代码会每次去建立新连接,就会代码一些开销,这个得去看一下 Rails 源码了。但应该都不会出现你说的“爆了”吧,连接池用的太多的话,最多是其他线程需要等待一会儿才能拿到连接。

tony612 回复

thank you.

tony612 回复
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 878
def establish_connection(config)
  resolver = ConnectionSpecification::Resolver.new(Base.configurations)
  spec = resolver.spec(config)

  remove_connection(spec.name)

  message_bus = ActiveSupport::Notifications.instrumenter
  payload = {
    connection_id: object_id
  }
  if spec
    payload[:spec_name] = spec.name
    payload[:config] = spec.config
  end

  message_bus.instrument("!connection.active_record", payload) do
    owner_to_pool[spec.name] = ConnectionAdapters::ConnectionPool.new(spec)
  end

  owner_to_pool[spec.name]
end

remove_connection(spec_name)

Remove the connection for this class. This will close the active connection and the defined connection (if they exist). The result can be used as an argument for establish_connection, for easily re-establishing the connection.

tony612 回复

好像没影响。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号