【问题标题】:How can I check the connection of Mongoid如何检查 Mongoid 的连接
【发布时间】:2015-04-11 08:20:05
【问题描述】:

Mongoid 有没有类似ActiveRecord::Base.connected? 的方法? 我想检查连接是否可以访问。

【问题讨论】:

    标签: mongodb connection mongoid database


    【解决方案1】:

    我们想为正在运行的 Mongoid 客户端实施健康检查,告诉我们已建立的连接是否仍然存在。这是我们想出的:

    Mongoid.default_client.database_names.present?
    

    基本上,它需要您当前的客户端并尝试查询其连接服务器上的数据库。如果此服务器已关闭,您将遇到超时,您可以抓住它。

    【讨论】:

      【解决方案2】:

      我的解决方案:

          def check_mongoid_connection
              mongoid_config = File.read("#{Rails.root}/config/mongoid.yml")
              config = YAML.load(mongoid_config)[Rails.env].symbolize_keys
              host, db_name, user_name, password = config[:host], config[:database], config[:username], config[:password]
              port = config[:port] || Mongo::Connection::DEFAULT_PORT
      
              db_connection = Mongo::Connection.new(host, port).db(db_name)
              db_connection.authenticate(user_name, password) unless (user_name.nil? || password.nil?)
              db_connection.collection_names
              return { status: :ok }
          rescue Exception => e
              return { status: :error, data: { message: e.to_s } }
          end
      

      【讨论】:

        【解决方案3】:

        snrlx 的回答很棒。

        我在我的 puma 配置文件中使用以下内容,仅供参考:

        before_fork do
          begin
            # load configuration
            Mongoid.load!(File.expand_path('../../mongoid.yml', __dir__), :development)
        
            fail('Default client db check failed, is db connective?') unless Mongoid.default_client.database_names.present?
          rescue => exception
            # raise runtime error
            fail("connect to database failed: #{exception.message}")
          end
        end
        

        需要提醒的是默认server_selection_timeout30 seconds,至少在开发中对于db状态检查来说太长了,你可以在你的mongoid.yml中修改它。

        【讨论】:

          猜你喜欢
          • 2014-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-09
          • 1970-01-01
          相关资源
          最近更新 更多