Node.js阻止事件循环
Node.js blocking the event loop?
我正在编写一个API,并且我陷入了根据传入请求混合异步和同步代码的困境,请看下面的示例。
路由.js
module.exports = [
{
method: 'GET',
path: '/',
controller: 'main',
action: 'main',
description: 'lists the API functionality',
access: 'auth'
},
{
method: 'POST',
path: '/users',
controller: 'users',
action: 'create',
description: 'creates a new user',
fields: {
fullName: {
format: {
min: 2,
max: 64,
minWords: 2,
disableDoubleSpaces: true
},
description: 'the full name of the new user',
examples: 'Thomas Richards, Richard Jones, Michael J. Fox, Mike Vercoelen, John Johnson'
},
email: {
format: {
min: 2,
max: 64,
maxWords: 1,
match: 'email'
},
description: 'the email address of the new user',
examples: 'mike@grubt.com, lilly@gmail.com, thomas.richards@mail.com, peter@mymail.com'
},
password: {
format: {
min: 2,
max: 64
},
description: 'the password of the new user',
examples: '123abcdfg, 7373kEjQjd, #8klKDNfk'
}
}
}
];
routes.js文件基本上是API的一个非常重要的部分,它验证传入数据,路由到正确的控制器/操作,并定义该方法是公共的,还是需要身份验证(基本身份验证)。
api server.js
var http = require('http');
var url = require('url');
var os = require('os');
var dns = require('dns');
var apiServer = module.exports;
var routes = require('./routes.js'); // Routes file from above.
var req, res, controller, action, serverInfo, httpServer;
apiServer.start = function(){
prepare(function(){
httpServer = http.createServer(handleRequest).listen(3000);
});
};
//
// We need to do this function, we need the local ip address of the
// server. We use this local ip address in logs (mongoDb) so we can
// refer to the correct server.
//
function prepare(callback){
var serverName = os.hostname();
dns.lookup(serverName, function(error, address){
if(error){
throw error;
}
serverInfo = {
name: serverName,
address: address
};
callback();
});
}
function getRoute(){
// loops through routes array, and picks the correct one...
}
function getAuth(callback){
// parses headers, async authentication (mongoDB).
}
function getRequestData(callback){
// req.on('data') and req.on('end'), getting request data.
}
function parseRequestData(callback){
// parse request data at this point.
}
function validateRequestData(callback){
// loop through route fields (see routes.js) and validate this data with the ones
// from the request.
}
function requireControllerAndCallAction(){
// do actual job.
}
function handleRequest(request, response){
req = request;
res = response;
req.route = getRoute(); // First step for a request, syncronous.
if(req.route === false){
// 404...
}
// If in the routing schema access was "auth",
// this route requires authentication, so do that...
if(req.route.access === 'auth'){
getAuth(function(error, user){
if(error){ // 401 } else {
req.user = user;
}
}
}
if(req.method === 'POST' || req.method === 'PUT'){
// Async functions.
getRequestData(function(){
parseRequestData(function(){
validateRequestData(function(){
requireControllerAndCallAction();
});
});
});
} else {
requireControllerAndCallAction();
}
}
正如您所看到的,有些函数是异步的(getAuth、getRequestData),有些是同步的(parseRequestData、validateRequestData)。
现在是这样的:
请求1。附带POST方法、url"/users"和数据:
- fullName='Rick'
- 电子邮件:"rick@"
- 密码:"a"
因此,我们循环通过API的工作流程:
获取当前路由(控制器:用户,操作:创建)请参阅routes.js 中的第二个数组元素
获取请求数据并在回调时:a.解析数据b.验证数据
现在让我们想象一下,数据的验证需要5秒(这是延迟的,但只是举个例子),在验证过程中,一个新的请求进来了,直到前一个请求完成,新的请求才被处理,对吗?
如果它们是同步的,如果它们确实花了5秒,那么是的,对于该服务器实例,请求将被阻止。这就是为什么阻止调用(网络、数据库、文件系统等)是异步的至关重要。事件循环必须保持循环或整个服务器块。
http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
这篇文章的关键一行是:
…然而,除了你的代码之外,一切都是并行运行的
这意味着昂贵的I/O应该是异步的,但您的代码可能会阻塞。但是,它通常是昂贵的I/O,我们担心在服务器上阻塞。
"您的代码"通常只是处理来自长时间运行的I/O调用的回调,更新您的状态,然后启动另一个调用。但这就是它的美妙之处——当你更新你的状态时,它在主事件循环中,所以不需要多线程访问"你的"状态和代码。没有锁定,没有死锁等等…但异步和并行I/O的所有好处都是昂贵的。
另一个关键点(5秒的非IO工作会陷入其中)是:
除了I/O调用之外,Node.js希望所有请求都返回迅速地例如,CPU密集型工作应该分配给另一个可以与事件交互的过程,或者使用像WebWorkers这样的抽象。
此外,是否期望"auth"answers"POST"|"PUT"发生在同一请求中?如果是这样,您可能有问题。getAuth看起来是异步的,但随后您立即转到req.method检查。到那时,getAuth仍然可以工作。如果您想对POST和PUT进行身份验证,那么可能需要用getAuth-async方法封装异步方法块。
- 事件循环、回调队列和 Javascript 的单线程是如何连接的
- JavaScript运行时事件循环现有技术
- 事件循环的MEAN.JS setInterval进程(从另一个服务器获取数据)
- 页面卸载期间的JavaScript事件循环
- Node.js阻止事件循环
- 了解执行模型和事件循环
- 什么是“;Promise在事件循环的同一个循环上点火“;意思是
- JS调试器是否挂起整个JS事件循环
- js事件循环是否意味着可以为临时暂存空间使用全局变量
- 在 Web 浏览器中收集有关事件循环的信息
- 检测事件循环“滞后”
- “旋转事件循环”是什么意思
- 如何在 nodejs 中维护事件循环中的持久数据
- DOMNode插入的事件循环
- Javascript事件循环任务队列溢出是否可能
- JavaScript 中的事件处理程序如何由事件循环处理
- Node.js 不是文件上传(以及所有基于事件循环的语言)的好选择 - 这是真的
- 为什么 while 循环会阻塞事件循环
- node.js事件循环何时终止
- C#“;事件循环”;与JavaScript“相比较;事件循环”;