如何让nodejs服务器优雅地退出

假设我们启动了一个服务器,接收到了一些客户端的请求,这时候,如果我们想修改一个代码发布,需要重启服务器,怎么办?假设我们有以下代码。

server.js

const net = require('net');
const server = net.createServer().listen(80);

client.js

const net = require('net');
net.connect({port:80})

如果我们直接杀死进程,那么存量的请求就会无法正常被处理。这会影响我们的服务质量。本文介绍如何使nodejs在重启时优雅地退出,所谓优雅,即让nodejs进程处理完存量请求后再退出。这关键的地方在于nodejs提供的api server.close()。我们看一下这api的介绍。

Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. The optional callback will be called once the 'close' event occurs. Unlike that event, it will be called with an Error as its only argument if the server was not open when it was closed.

当我们使用close关闭一个server时,server会等所有的连接关闭后才会触发close事件。我们看一下源码。

Server.prototype.close = function(cb) {
  // 触发回调
  if (typeof cb === 'function') {
    if (!this._handle) {
      this.once('close', function close() {
        cb(new errors.Error('ERR_SERVER_NOT_RUNNING'));
      });
    } else {
      this.once('close', cb);
    }
  }
  // 关闭底层资源
  if (this._handle) {
    this._handle.close();
    this._handle = null;
  }
  // 判断是否需要立刻触发close事件
  this._emitCloseIfDrained();
  return this;
};

// server下的连接都close后触发server的close事件
Server.prototype._emitCloseIfDrained = function() {
  // 还有连接则先不处理
  if (this._handle || this._connections) {
     return;
  }

  const asyncId = this._handle ? this[async_id_symbol] : null;
  nextTick(asyncId, emitCloseNT, this);
};
Socket.prototype._destroy = function(exception, cb) {
  ...
  // socket所属的server
  if (this._server) {
    // server下的连接数减一
    this._server._connections--;
    // 是否需要触发server的close事件,当所有的连接(socket)都关闭时才触发server的是close事件
    if (this._server._emitCloseIfDrained) {
      this._server._emitCloseIfDrained();
    }
  }
};

从源码中我们看到,nodejs会先关闭server对应的handle,所以server不会再接收新的请求了。但是server并没有触发close事件,而是等到所有连接断开后才触发close事件,这个通知机制给了我们一些思路。我们可以监听server的close事件,等到触发close事件后才退出进程。

const net = require('net');
const server = net.createServer().listen(80);
server.on('close', () => {
  process.exit();
});
// 防止进程提前挂掉
process.on('uncaughtException', () => {

});
process.on('SIGINT', function() {
  server.close();
})

我们首先监听SIGINT信号,当我们使用SIGINT信号杀死进程时,首先调用server.close,等到所有的连接断开,触发close时候时,再退出进程。我们首先开启服务器,然后开启两个客户端。接着按下ctrl+c,我们发现这时候服务器不会退出,然后我们关闭两个客户端,这时候server就会优雅地退出。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值