【问题标题】:Ruby mongo driver: Catch MongoDB connection errors after a few seconds?Ruby mongo 驱动程序:几秒钟后捕获 MongoDB 连接错误?
【发布时间】:2020-03-16 07:13:10
【问题描述】:

我正在使用我的 Ruby mongo 驱动程序执行此查询:

begin
  User.collection.find({}).count()
rescue => e
  Rails.logger.error e.to_s
end

我想捕获此操作失败的所有情况。它失败的主要原因是服务器不可用。

例如,我偶尔看到的错误之一是:

Mongo::Error::NoServerAvailable (No server is available matching preference: #<Mongo::ServerSelector::Primary:0x70302744731080 tag_sets=[] max_staleness=nil> using server_selection_timeout=30 and local_threshold=0.015)

我想在 6 秒后捕获错误。

从the docs 我看到有几个不同的超时选项(connect_timeout、server_selection_timeout、socket_timeout)。但我不确定要通过哪个,以及如何通过它们。

【问题讨论】:

    标签: ruby mongodb


    【解决方案1】:

    你在正确的轨道上。 server_selection_timeout 在这种情况下是正确的选项——它告诉驱动程序在超时之前等待多长时间才能找到合适的服务器。您可以在 Mongoid 配置文件 (config/mongoid.yml) 的新客户端上设置该选项。

    您希望您的配置文件看起来像这样:

    development: # (or production or whatever environment you're using)
      clients:
        default:
          # your default client here
        new_client: # the name of your new client with different options
          database: mongoid
          hosts:
            - localhost:27017
          options:
            server_selection_timeout: 6
            ...
    

    阅读Mongoid Configuration documentation 以了解有关设置配置文件的更多信息。

    然后,您想使用您定义的新客户端来执行查询,并挽救任何Mongo::Error::NoServerAvailable 错误。

    begin
      User.with(client: 'new_client').collection.find({}).count()
    rescue Mongo::Error::NoServerAvailable => e
      # perform error handling here
    end
    

    请注意,这会启动一个新的Mongo::Client 实例,如果重复执行,这是一项昂贵的操作。我建议您在完成使用后关闭额外的客户端,如下所示:

    Mongoid::Clients.with_name('new_client').close
    

    【讨论】:

    • 非常感谢@egiurleo。您的回答非常有用,应该留给其他会找到这篇文章的人。但我对在我的请求期间设置/覆盖超时特别感兴趣。如果可能,您能否通过评论如何在查询中将server_selection_timeout 键作为参数传递来扩展答案?
    • 感谢@JohnSmith1976 的澄清!我更新了我的回复以反映您的实际问题。让我知道这是否有帮助!
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多