栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Node.js是否可以一一处理客户端请求?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Node.js是否可以一一处理客户端请求?

Node.js是否可以一一处理客户端请求?

是和否。node.js运行您的JS单线程。这意味着在任何给定时间仅运行一个JS执行线程。因此,如果您有两个这样的要求:

// don't use this in real pre, it's to simulate a pointfunction spin(t) {    var start = Date.now();    while (Date.now() < start + t) {}}app.post("/route1", req, res) {    console.log("starting processing of /route1 request");    // simulate taking several seconds of pure CPU to make a response    spin(2000);    res.send("done 1");    console.log("finished processing of /route1 request");}app.post("/route2", req, res) {    console.log("starting processing of /route2 request");    // simulate taking several seconds of pure CPU to make a response    spin(2000);    res.send("done 2");    console.log("finished processing of /route2 request");}

并且/ route1请求之后紧接着是/ route2请求,然后node.js服务器将处理/
route1请求,直到该请求完成后才能执行其他任何操作,因为CPU一直处于忙碌状态。

因此,这将产生如下日志:

starting processing of /route1 requestfinished processing of /route1 requeststarting processing of /route2 requestfinished processing of /route2 request

但是,纯粹出于CPU原因,请求花费很长时间是相对罕见的。请求通常涉及某种I / O(要读取的文件,数据库查询,要联系的其他服务器等)。如果该I /
O是使用异步IO而不是同步IO以异步方式完成的,则多个请求可以轻松地同时进行,并且可以同时进行,因为node.js服务器正在等待对于I /
O请求完成,可以免费服务其他请求,也可以服务其他请求。

因此,如果您具有以下服务器代码:

app.post("/route1", req, res) {    console.log("starting processing of /route1 request");    // simulate taking several seconds of pure CPU to make a response    request('http://www.google.com', function (error, response, body) {        if (!error && response.statusCode == 200) { res.send("done 1"); console.log("finished processing of /route1 request");        }    });}app.post("/route2", req, res) {    console.log("starting processing of /route2 request");    // simulate taking several seconds of pure CPU to make a response    request('http://www.google.com', function (error, response, body) {        if (!error && response.statusCode == 200) { res.send("done 2"); console.log("finished processing of /route2 request");        }    });}

并且/ route1请求之后紧接着是/ route2请求,那么您可能会看到此日志(无法保证/ route1和/ route2响应完成的顺序-
它们可以按任何顺序排列),但是两个响应都将是并行处理:

starting processing of /route1 requeststarting processing of /route2 requestfinished processing of /route1 requestfinished processing of /route2 request

如果您的node.js代理服务器似乎表现出串行处理行为而不是并行处理行为,则可能是在实现代理方面存在某种实现问题,因为它肯定能够在其中包含多个请求同时飞行。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469172.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号