mongodb - 如何在 Sails 0.12 中通过请求(在部分离线的情况下)连接到远程数据库
问题描述
我的 PC 在 Kiosk 模式下运行(自助服务亭)。它的互联网连接较弱,所以我使用本地 MongoDB 服务器来处理所有数据。但有时(例如每天)我想将统计数据和其他内容发送到远程数据库。当我启动 PC 时,当互联网连接断开时,我收到以下消息:
error: A hook (`orm`) failed to load!
error: Error: Failed to connect to MongoDB. Are you sure your configured Mongo instance is running?
Error details: { MongoError: connection 1 to ds241489.mlab.com:41489 timed out
at Function.MongoError.create (/home/nevada/v4/node_modules/mongodb-core/lib/error.js:29:11)
at Socket.<anonymous> (/home/nevada/v4/node_modules/mongodb-core/lib/connection/connection.js:186:20)
...
然后 Sails 崩溃并且浏览器向用户显示错误消息
连接.js:
mlab: {
adapter: 'sails-mongo',
host: 'ds241489.mlab.com',
port: *****,
user: '******',
password: '************',
database: '******'
}
模型/Remote.js:
module.exports = {
connection: 'mlab',
attributes: {
// Some stuff here
}
};
互联网可用时一切正常,但是当 PC 离线时,服务器拒绝启动。如何根据用户的请求跳过与(远程)数据库的自动连接,然后(尝试)手动连接?
解决方案
I haven't implemented this myself, but I would do one of two things here:
Set up a separate
cron
or other type of scheduled task to run every hour or so. This would then check for internet, and if internet connects successfully, run the DB-sync script. Of course inside a big try/catch to gracefully handle internet disconnect half way through.Set up an event-listener on the host/kiosk system, that listens for an event indicating that the OS has internet connection again. When that happens, try to run the script mentioned above.
Number one is the most likely candidate in my book, and I'd even throw in a Sails module to keep all logic in the controllers and config. sails-hook-cron
(GitHub) is a very popular hook you can use to configure your cron-job in the config/cron.js
file, and use it in a controller of your choosing.
Set up your application to NOT connect to Mlab automatically. Only do that in the sync-script, and the app should start without a hitch, regardless of your internet connection.
推荐阅读
- node.js - Node JS Discord 日志 guildMemberUpdate
- react-native - 单元测试开玩笑酶在 Formik 'resetForm' 上引发错误
- java - Spring Cloud Configuration - 访问所有微服务中的共享属性文件
- python - 使用open-cv从左到右的vstack矩形
- java - 如何在 agora.io Java 中为每个用户生成唯一的频道名称?
- python - 我有一个家庭作业来编写一个素数生成器
- sql-server - 根据列中的值将SQL中的一列拆分为多列
- java - Spring Actuator - 服务发现 - /health "description":"Discovery Client not initialized","status":"UNKNOWN"
- c++ - 有人可以解释为什么我的程序没有正确排序值吗?
- jdbc - 如何编写 Kafka Connect 查询以使用时间戳模式查询两个特定日期之间的数据