【问题标题】:NodeJS HTTPServer takes a long time to closeNodeJS HTTP Server 需要很长时间才能关闭
【发布时间】:2012-01-05 22:55:25
【问题描述】:

我正在开发一个 Zappa 应用程序,我目前正在尝试制作一个小监视脚本来停止服务器,清除 require.cache 然后在文件更改时重新要求并重新启动服务器,例如:

# watch all dependent files
for file of require.cache
  fs.watch file, ->
    # attach a handler to 'close'
    # -- here's the issue: this takes far too long to trigger
    server.on 'close', ->
      server = require './server'
      server.start()

      # log the new server's id
      console.log server.id

    # stop the current server instance
    server.stop()

    # clear require's cache
    delete require.cache[f] for f of require.cache

我的请求处理程序中还有一个 console.log server.id 行,因此我可以检查 ID 是否匹配。

所以,发生的事情是:当我更改一个依赖项时,服务器停止,一个新的启动并记录新的 ID,这都是肉汁。但是,在之后的随机时间内,对服务器的请求仍然记录旧 ID,表明旧的侦听器仍然以某种方式连接。最终,监听器似乎“切换”并记录了新 ID。

更新: 这似乎与close 事件有关(不出所料) - 如果我将一个简单的console.log 'close' 回调附加到close 事件,则ID 在@987654327 之后开始更改@ 出现。但是,触发close 事件可能需要很长时间(10 秒以上),为什么需要这么长时间?

【问题讨论】:

    标签: node.js express zappa


    【解决方案1】:

    根据node.js docs

    server.close()

    阻止服务器接受新连接。参见 net.Server.close()。

    因此,您的服务器将停止接受新连接,但在关闭当前连接之前它不会真正关闭(并发出close 事件)。我的猜测是你有客户端连接到它,可能是 keep-alive 请求。

    【讨论】:

    【解决方案2】:

    我正在寻找同样的问题。为您和其他搜索此问题的人提供解决方案:

    如果这在您的项目中不是问题,您可以立即关闭所有连接。这完全解决了我的关闭问题。

    app.use((req, res, next) => {
        res.setHeader('Connection', 'close');
        next();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      相关资源
      最近更新 更多