首页 > 解决方案 > Ruby mongo 驱动程序:几秒钟后捕获 MongoDB 连接错误?

问题描述

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

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 秒后捕获错误。

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

标签: rubymongodb

解决方案


你在正确的轨道上。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 配置文档以了解有关设置配置文件的更多信息。

然后,您想使用您定义的新客户端来执行您的查询,并挽救任何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

推荐阅读