传统 web 服务器是多线程的,每个会话通常都有自己的线程。该方法很有效,但当会话空闲时,它会要求 Web 服务器分配未被使用的资源。这些空闲会话的开销,使得扩展服务器来处理需求峰值变得更加困难。
另一方面,Node 引擎包含一个线程,用于应对操作系统发出的所有事件处理通知。如果该操作是异步的(例如,调用数据库或 REST 接口),Node 引擎会要求操作系统在准备好处理调用时通知它(比如在数据从数据库或 REST 调用传来时)。在此期间,Node 事件循环会前进到需要执行的下一个操作。
- function asyncCode(arg1, arg2, callback) {
- // Do whatever the function does here. When it's complete, it should
- // invoke the callback function, returning a (hopefully null)
- // JavaScript Error object and the results of this function.
- return callback(error, results);
- }
- asyncCode(x, 37, function(error, results) {
- if (error != null)
- // Handle the error if there is one
- else
- // Otherwise do whatever we want with the results
- });
- Hello
- there,
- world!
- world!
- Hello
- there,
来源: http://www.ibm.com/developerworks/cn/analytics/library/ba-cn-spark-ibm-lsf-integration/index.html