NodeJS HTTPServer 需要很长时间才能关闭
我正在开发一个 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
事件,'close'
出现后ID开始变化。但是,close
事件可能需要很长时间(10s+)才能触发,为什么会花这么长时间?
I'm working on a Zappa app, and I'm currently trying to make a little watch script that stops the server, clears require.cache
then re-requires and restarts the server when a file changes, something like:
# 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
I also have a console.log server.id
line in my request handler so I can check if the IDs match.
So, what happens is: when I change a dependency, the server stops, a new one starts and the new ID is logged, which is all gravy. However, for a random amount of time after, requests to the server still log the old ID, indicating that the old listener is still attached somehow. Eventually, the listener seems to 'switch over' and the new ID is logged.
Update: it seems this is related to the close
event (unsurprisingly) - if I attach a simple console.log 'close'
callback to the close
event, the ID starts changing after 'close'
appears. However, it can take a long time (10s+) for the close
event to be fired, why might it take so long?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 node.js 文档:
因此,您的服务器将停止接受新连接,但在当前连接关闭之前,它实际上不会关闭(并发出
close
事件)。我的猜测是您有客户端连接到它,可能有keep-alive
请求。According to the node.js docs:
So, your server would stop accepting new connections, but it won't actually close (and emit
close
event) until current connections are closed. My guess is that you have clients connected to it, perhaps withkeep-alive
requests.我正在寻找同样的问题。为了给您和其他正在寻找此解决方案的人提供一个解决方案:
如果这不是您的项目中的问题,您可以立即关闭所有连接。这完全解决了我的关闭问题。
I was searching for the same problem. To give you and others searching for this a solution:
You can close all connections immediately, if this is not a problem in your project. This solves the closing problem for me completly.