Node.js Web 服务器中的并行请求 [英] Parallel requests in Node.js web server

查看:26
本文介绍了Node.js Web 服务器中的并行请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个运行 Node.js 的网络服务器,那么我能同时处理多个请求吗?从我的初步测试中可以看出,Node 主要是单线程的,目前只能处理一个 HTTP 请求.但是如果一个请求需要很长时间才能完成(例如,上传大数据),那么所有其他请求都必须等待.

If I have a web server that runs Node.js, then will I be able to serve multiple requests at the same time? From my preliminary tests I can see than Node being primarily single threaded can process only one HTTP request at the moment. But if one request takes too long to complete (for example, uploading of a large data) then all the other request have to wait.

这种情况有解决方法吗?我们可以编写代码使其可以同时处理多个 HTTP 请求吗?

Is there an workaround for this situation? Can we write the code such that it can server multiple HTTP requests at the same time?

推荐答案

Node 是单线程的这一事实并不一定意味着它一次只能处理 1 个请求.

The fact that Node is single threaded does not necessarily mean it can only process 1 request at a time.

Node 中的很多事物都是有意异步的;例如许多文件系统操作、数据库查询等.这是以下心态:

A lot of things in Node are purposely asynchronous; such as many file system operations, DB queries etc. This is the mindset of:

我知道你会花一些时间来做这件事,所以当你完成后给我打电话,同时我会更好地利用我的单线程操作,而不是等待你来完成.

I know you're going to take some time to do this, so call me when you're done and in the meantime I'm going to put my single-thread of operation to some better use, rather than waiting for you to complete.

正是在这一点上处理其他工作(可以是其他请求).当然,如果他们然后不得不执行一个异步操作,操作流程可能会回到我们之前暂停的地方,因为另一个操作已经完成.

It is at that point that other work (which can be other requests) are processed. Of course, if they then have to perform an asynchronous operation, the flow of operation might return to where we suspended ourselves earlier, because the other operation has completed.

在您进行大型上传的情况下,传入的流被异步处理并通过 进行管理数据事件.如果你想把这个流写入磁盘,同样,写入可以异步执行;即在文件上传过程中有一些点可以处理其他请求.

In your situation where a large upload is taking place, the incoming stream is processed asynchronously and is managed through the data event. If you want to write this stream to disk, again, the writing can be performed asynchronously; i.e. there are points during the file upload process where other requests could be processed.

多线程操作只有在你有多个 CPU 内核时才有好处;那么每个操作线程都可以在不同的内核上运行.为此,Node 具有 cluster 模块,您应该查看该模块.

Having multiple threads of operation is only beneficial if you have multiple CPU cores; then each thread of operation can run on a different core. To do this, Node has the cluster module, which you should look at.

这篇关于Node.js Web 服务器中的并行请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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