ruby - 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
)。但我不确定要通过哪个,以及如何通过它们。
解决方案
你在正确的轨道上。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
推荐阅读
- javascript - 在结果页面上隐藏 CSS 类
- compiler-construction - 使用 Bison 编写解析器时的冲突
- spring - Spring数据休息,关系属性的默认值
- sql - What is the difference between LIKE '[A-D]%' ; and BETWEEN 'A' AND 'D' ; in SQL Server
- angular - 在 Angular 6 中重用组件 html
- vba - 如何创建一个内置用户表单的excel
- python - 如何在 Python 的哈希表中实现动态哈希?
- java - 无法通过套接字在android中的图像视图上显示图像
- spring-boot - MockMVC 测试如何验证答案
- android - RecyclerView 与 cursor Adapter 的实现