本文转载自微信公众号「编程杂技」,作者theanarkh。转载本文请联系编程杂技公众号。
假设我们启动了一个服务器,接收到了一些客户端的请求,这时候,如果我们想修改一个代码发布,需要重启服务器,怎么办?假设我们有以下代码。
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就会优雅地退出。
在VMworld 2020,VMware宣布与NVIDIA进行全面合作,共同推出新一代的混合云架构...
【51CTO.com快译】数字化转型使应用程序领导人必须找到有效的方法来更新改造遗留...
在疫情的影响下,人们的工作和生活方式在过去的一年发生了前所未有的变化。为了...
根据TrendForce的最新调查,自2020年初以来,COVID-19流感大流行加速了世界各地...
人头马君度(Rmy Cointreau)的历史非常重要,这家酒业公司以将最好的酒陈化100年...
根据调查,随着用户对计算能力、存储和网络容量的需求增长,服务器需求比经济不...
2020年以来,由疫情停工减产所导致的缺芯困局影响着全球汽车发展,而本以为2021...
2020年11月26日深圳潮数科技于石家庄成功召开数据安全 新时代新基建信息应用之基...
时间真快呀!转眼又至周一。让我们卯足干劲继续前行,先来看看上周有哪些不容错...
本文中的五个步骤有助于您掌握转型的总体需求,并有助于您处理一些真正重要的事...