繁体   English   中英

ActiveRecord::ConnectionNotEstablished:在登台时找不到“阅读”角色的“主要”连接池

[英]ActiveRecord::ConnectionNotEstablished: No connection pool with 'primary' found for the 'reading' role on staging

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

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

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
``


原因是 rails 的自动连接切换

我在config/environments/staging.rb评论了以下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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM