简体   繁体   English

Node JS Mongoose-如果节点服务器无法连接到数据库,最佳实践是什么?

[英]Node JS Mongoose - What is best practices if node server cannot connect to database?

I have multiple websites transmitting data to my server which in turn writes data to our mongo database. 我有多个网站将数据传输到服务器,然后服务器将数据写入我们的mongo数据库。 If the server cannot connect to the database, the server becomes useless. 如果服务器无法连接到数据库,则服务器将无用。

Currently, if a server cannot connect to the database, I am simply logging the error. 当前,如果服务器无法连接到数据库,我只是在记录错误。

mongoose.connection
  .once('open', () => { console.log('connected to database'); })
  .on('error', () => { console.log('database connection error'); });

My question is, what is best practice if a node server cannot connect to the database? 我的问题是,如果节点服务器无法连接到数据库,那么最佳实践是什么? Should I throw the error? 我应该抛出错误吗? Maybe shut down the server completely? 也许完全关闭服务器?

I'm assuming that the server you're talking about serves an API of some sort that the clients are connecting to. 我假设您正在谈论的服务器提供客户端连接到的某种API。

If that server cannot talk to the database, that sounds like a serious issue. 如果该服务器无法与数据库对话,这听起来像是一个严重的问题。 You will need to do a couple of things: 您将需要做几件事:

  1. The server needs to inform the clients that there's an issue. 服务器需要通知客户端有问题。 Hopefully your clients are written in such a way that they will gracefully handle this. 希望您的客户以这样的方式编写,以便他们能够妥善处理。

  2. Your server needs to log the details. 您的服务器需要记录详细信息。 Not just a message that says "database connection error", but all the error information. 不仅是显示“数据库连接错误”的消息,还包括所有错误信息。 You won't be able to troubleshoot without the details. 没有详细信息,您将无法进行故障排除。

  3. You probably need some sort of system to notify the system administrator in real time when the database goes down. 您可能需要某种系统来在数据库关闭时实时通知系统管理员。 This is crucial to getting the system back up and running as quickly as possible. 这对于尽快恢复系统运行至关重要。

It's difficult to answer more specifically than this, given the limited information you provided. 鉴于您提供的信息有限,因此很难比这更具体地回答。 Much of it will be specific to your server implementation. 其中大部分将特定于您的服务器实施。 For example, assuming you've written a RESTful API, the clients should probably be sent an HTTP status code of 500 (internal server error) and some descriptive information. 例如,假设您已经编写了RESTful API,则应该向客户端发送HTTP状态码500(内部服务器错误)和一些描述性信息。 If you've chosen some other API implementation, then your response will differ. 如果您选择了其他一些API实现,则您的响应将有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM