Ruby mongo驱动程序:几秒钟后捕获MongoDB连接错误?
我正在使用RubyRuby mongo驱动程序:几秒钟后捕获MongoDB连接错误?,ruby,mongodb,Ruby,Mongodb,我正在使用Rubymongo驱动程序执行此查询: 开始 User.collection.find({}).count() 救援=>e Rails.logger.error e.to_ 结束 我想了解所有操作失败的情况。它失败的主要原因是服务器不可用 例如,我偶尔看到的错误之一是: Mongo::Error::NoServerAvailable (No server is available matching preference: #<Mongo::ServerSelector::Pri
mongo
驱动程序执行此查询:
开始
User.collection.find({}).count()
救援=>e
Rails.logger.error e.to_
结束
我想了解所有操作失败的情况。它失败的主要原因是服务器不可用
例如,我偶尔看到的错误之一是:
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)
Mongo::Error::NoServerAvailable(没有可用的服务器匹配首选项:#使用服务器_选择_超时=30和本地_阈值=0.015)
我想在6秒钟后捕捉错误
从中我看到有几个不同的超时选项(
connect\u timeout
,server\u selection\u timeout
,socket\u timeout
)。但是我不知道该通过哪一个,以及如何通过它们。你走对了方向server\u selection\u 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
...
阅读以了解有关设置配置文件的更多信息
然后,您希望使用您定义的新客户机执行查询,并挽救任何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。你的答案非常有用,应该留给其他人找到这篇文章。但我特别感兴趣的是在请求期间设置/覆盖超时。如果可能的话,您可以通过评论如何将
服务器选择\u超时
键作为查询中的参数来扩展答案吗?感谢您澄清@JohnSmith1976!我更新了我的回答以反映您的实际问题。如果有帮助,请告诉我!