与 MongoDB 的连接是否在 process.exit() 上自动关闭? [英] Is a connection to MongoDB automatically closed on process.exit()?

查看:47
本文介绍了与 MongoDB 的连接是否在 process.exit() 上自动关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 mongodb 驱动程序从 Node.js 应用程序连接到 MongoDB 服务器.

I am using the mongodb driver to connect to a MongoDB server from a Node.js application.

假设我的应用程序崩溃了,或者我调用了 process.exit()没有之前关闭连接 - 它是否保持打开状态?是自动关闭的吗?如果是这样,谁在乎呢?节点.js?TCP/IP 堆栈?MongoDB?……?以及:什么时候会发生?

Supposed my application crashes, or I call process.exit(), without closing the connection previously - does it stay open? Is it closed automatically? If so, who cares about that? Node.js? The TCP/IP stack? MongoDB? …? And: When does that happen?

如果我点击 + 会有什么不同吗?

Does it make a difference if I hit <Ctrl>+<C>?

推荐答案

答案是.当您退出(或崩溃)时,数据库连接不会正常关闭.

The answer is no. DB connections don't gracefully shut down when you exit (or crash).

要做到这一点,您应该使用类似于:

To do that you should use something similar to:

// Create a function to terminate your app gracefully:
function gracefulShutdown(){
    // First argument is [force], see mongoose doc.
    mongoose.connection.close(false, () => {
      console.log('MongoDb connection closed.');
    });
  });
}

// Ask node to run your function before exit:

// This will handle process.exit():
process.on('exit', gracefulShutdown);

// This will handle kill commands, such as CTRL+C:
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
process.on('SIGKILL', gracefulShutdown);

// This will prevent dirty exit on code-fault crashes:
process.on('uncaughtException', gracefulShutdown);

还有一些包可以处理这种行为,但这通常非常简单,而且易于实现.

There are also some packages to handle this behavior, but this is usually very straightforward, and simple to implement.

这篇关于与 MongoDB 的连接是否在 process.exit() 上自动关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆