【问题标题】:ActiveRecord::ConnectionNotEstablished: No connection pool with 'primary' found for the 'reading' role on stagingActiveRecord::ConnectionNotEstablished: 暂存时未找到“读取”角色的“主”连接池
【发布时间】:2021-10-05 11:12:07
【问题描述】:

我正在将我们当前的 Rails 应用程序 (v 6.0.3.4) 迁移到一个多租户应用程序,其中每个客户端都将拥有自己的数据库。该代码在我的本地环境中运行良好,但在暂存时会出现ActiveRecord::ConnectionNotEstablished: No connection pool with 'primary' found for the 'reading' role 错误。

我根据子域在机架级别选择数据库。

module Middlewares
  class Multitenancy
    def initialize(app)
      @app = app
    end
 
    def call(env)
      @env = env
      
      database = { writing: "primary_#{subdomain}".to_sym, reading: "replica_reader_#{subdomain}".to_sym }
      

      ActiveRecord::Base.connected_to(database: database) do
        @app.call(env)
      end
    end

    private

    def subdomain
       ActionDispatch::Http::URL.extract_subdomain(@env['HTTP_HOST'], 1) unless @env['HTTP_HOST'].nil?
    end
  end
end

数据库.yml

default: &default
  adapter: mysql2
  encoding: utf8
#  reconnect: false
  host: <%= ENV.fetch("MYSQL_HOST") { '127.0.0.1' } %> # 127.0.0.1 to force use tcp ip instead of unix socket
  database:  <%= ENV.fetch("MYSQL_DB") { 'development' } %>
  pool:  <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } * 30 %>
  username: <%= ENV.fetch("MYSQL_USER") { 'root' } %>
  password: <%= ENV.fetch("MYSQL_PASSWORD") { '' } %>
  port: <%= ENV.fetch("MYSQL_PORT") { '3306' } %>
  variables:
    sql_mode: TRADITIONAL

staging:
  primary_subdomain_1:
    <<: *default
    host: <%= ENV.fetch("MYSQL_HOST") %>
  replica_reader_subdomain_1:
    <<: *default
    host: <%= ENV.fetch("MYSQL_HOST_REPLICA") %>
    replica: true
  primary_subdomain_2:
    <<: *default
    host: %= ENV.fetch("MYSQL_HOST2") %>
  replica_reader_subdomain_2:
    <<: *default
    host: %= ENV.fetch("MYSQL_HOST2_REPLICA") %>
    replica: true
``


【问题讨论】:

  • 您的代码中是否有任何地方使用角色:reading 连接到数据库,例如ActiveRecord::Base.connected_to(role: :reading) do ...
  • 不,我们不会在应用程序的任何地方使用上述内容。

标签: ruby-on-rails multi-tenant ruby-on-rails-6


【解决方案1】:

原因是 rails 的automatic connection switching

我在config/environments/staging.rb 中评论了以下几行,它起作用了。

config.active_record.database_selector = { delay: 2.seconds }
config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session

【讨论】:

    猜你喜欢
    • 2021-04-11
    • 2021-01-01
    • 2015-09-12
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 2012-04-05
    • 2019-07-08
    相关资源
    最近更新 更多