跳至内容 跳至搜索

Active Record 连接处理器

ConnectionHandlerConnectionPool 对象的集合。它用于维护连接到不同数据库的独立连接池。

例如,假设你有 5 个模型,具有以下层级结构

class Author < ActiveRecord::Base
end

class BankAccount < ActiveRecord::Base
end

class Book < ActiveRecord::Base
  establish_connection :library_db
end

class ScaryBook < Book
end

class GoodBook < Book
end

并且有一个如下所示的 database.yml 文件

development:
  database: my_application
  host: localhost

library_db:
  database: library
  host: some.library.org

在开发环境中,你的主数据库是“my_application”,但 Book 模型连接到名为“library_db”的独立数据库(这甚至可以是不同机器上的数据库)。

Book、ScaryBook 和 GoodBook 都将使用同一个连接池连接到“library_db”,而 Author、BankAccount 和你创建的任何其他模型将使用连接到“my_application”的默认连接池。

各种连接池由 ConnectionHandler 的单个实例管理,该实例可以通过 ActiveRecord::Base.connection_handler 访问。所有 Active Record 模型都使用此处理器来确定它们应该使用的连接池。

ConnectionHandler 类不与 Active 模型耦合,因为它不了解模型。模型需要向处理器传递一个连接规范名称,以便查找正确的连接池。

方法
A
C
E
F
N
R

类公共方法

new()

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 76
def initialize
  # These caches are keyed by pool_config.connection_name (PoolConfig#connection_name).
  @connection_name_to_pool_manager = Concurrent::Map.new(initial_capacity: 2)
end

实例公共方法

active_connections?(role = nil)

如果 ConnectionHandler 正在管理的连接池中有任何活动的连接,则返回 true。

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 157
def active_connections?(role = nil)
  each_connection_pool(role).any?(&:active_connection?)
end

clear_active_connections!(role = nil)

将当前线程正在使用的任何连接返回到连接池。

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 162
def clear_active_connections!(role = nil)
  each_connection_pool(role).each do |pool|
    pool.release_connection
    pool.disable_query_cache!
  end
end

clear_all_connections!(role = nil)

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 176
def clear_all_connections!(role = nil)
  each_connection_pool(role).each(&:disconnect!)
end

clear_reloadable_connections!(role = nil)

清除所有连接池中可重载的连接缓存。

有关详细信息,请参阅 ConnectionPool#clear_reloadable_connections!

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 172
def clear_reloadable_connections!(role = nil)
  each_connection_pool(role).each(&:clear_reloadable_connections!)
end

connected?(connection_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)

如果此类可访问的连接已被打开,则返回 true。

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 198
def connected?(connection_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)
  pool = retrieve_connection_pool(connection_name, role: role, shard: shard)
  pool && pool.connected?
end

connection_pool_list(role = nil)

返回连接处理器和给定角色的连接池。如果传入 :all,将返回连接处理器所属的所有连接池。

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 95
def connection_pool_list(role = nil)
  if role.nil? || role == :all
    connection_name_to_pool_manager.values.flat_map { |m| m.pool_configs.map(&:pool) }
  else
    connection_name_to_pool_manager.values.flat_map { |m| m.pool_configs(role).map(&:pool) }
  end
end

connection_pools(role = nil)

establish_connection(config, owner_name: Base, role: Base.current_role, shard: Base.current_shard, clobber: false)

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 115
def establish_connection(config, owner_name: Base, role: Base.current_role, shard: Base.current_shard, clobber: false)
  owner_name = determine_owner_name(owner_name, config)

  pool_config = resolve_pool_config(config, owner_name, role, shard)
  db_config = pool_config.db_config

  pool_manager = set_pool_manager(pool_config.connection_descriptor)

  # If there is an existing pool with the same values as the pool_config
  # don't remove the connection. Connections should only be removed if we are
  # establishing a connection on a class that is already connected to a different
  # configuration.
  existing_pool_config = pool_manager.get_pool_config(role, shard)

  if !clobber && existing_pool_config && existing_pool_config.db_config == db_config
    # Update the pool_config's connection class if it differs. This is used
    # for ensuring that ActiveRecord::Base and the primary_abstract_class use
    # the same pool. Without this granular swapping will not work correctly.
    if owner_name.primary_class? && (existing_pool_config.connection_descriptor != owner_name)
      existing_pool_config.connection_descriptor = owner_name
    end

    existing_pool_config.pool
  else
    disconnect_pool_from_pool_manager(pool_manager, role, shard)
    pool_manager.set_pool_config(role, shard, pool_config)

    payload = {
      connection_name: pool_config.connection_descriptor.name,
      role: role,
      shard: shard,
      config: db_config.configuration_hash
    }

    ActiveSupport::Notifications.instrumenter.instrument("!connection.active_record", payload) do
      pool_config.pool
    end
  end
end

flush_idle_connections!(role = nil)

断开所有当前空闲的连接。

有关详细信息,请参阅 ConnectionPool#flush!

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 183
def flush_idle_connections!(role = nil)
  each_connection_pool(role).each(&:flush!)
end

remove_connection_pool(connection_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 203
def remove_connection_pool(connection_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)
  if pool_manager = get_pool_manager(connection_name)
    disconnect_pool_from_pool_manager(pool_manager, role, shard)
  end
end

retrieve_connection_pool(connection_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard, strict: false)

检索连接池的次数非常多,因此我们将其缓存到 @connection_name_to_pool_manager 中。这使得在进程预热后,检索连接池的复杂度为 O(1)。当建立或移除连接时,我们会使缓存失效。

# File activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb, line 212
def retrieve_connection_pool(connection_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard, strict: false)
  pool_manager = get_pool_manager(connection_name)
  pool = pool_manager&.get_pool_config(role, shard)&.pool

  if strict && !pool
    selector = [
      ("'#{shard}' shard" unless shard == ActiveRecord::Base.default_shard),
      ("'#{role}' role" unless role == ActiveRecord::Base.default_role),
    ].compact.join(" and ")

    selector = [
      (connection_name unless connection_name == "ActiveRecord::Base"),
      selector.presence,
    ].compact.join(" with ")

    selector = " for #{selector}" if selector.present?

    message = "No database connection defined#{selector}."

    raise ConnectionNotDefined.new(message, connection_name: connection_name, shard: shard, role: role)
  end

  pool
end