传统node单线程缺陷

下面的express程序可以看出nodejs单线程的缺陷,当访问主页面localhost:3000时,doWork(5000)方法会暂停5秒钟。

由于长时间的等待时间会使得node陷入到停顿的状态。当其他的请求来的时候,也只能够等待。例如当访问后立即访问localhost:3000/fast,只能够等待一段时间。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
const express = require('express'); const app = express(); function doWork(duration){
 const start = Date.now();  while(Date.now()-start
{
 doWork(5000);  res.send("i like jonson") }) app.get('/fast',(req,res)=>{
 res.send("i like jonson") }) app.listen(3000);

cluster多线程node增强node表现

使用nodejs内置的cluster module可以让多个node实例同时运行,管理多个node实例。

cluster管理多个node实例。cluster manager实例与child实例都会调用此文件中的代码。

通过cluster.isMaster将两者区分开。

cluster manager 中cluster.isMaster为true。
child实例实例中cluster.isMaster为false。

cluster.fork()代表新开一个child 实例。

下面的代码在一开始,cluster manager实例就新开了4个child 实例。

所以即便是一个child停顿不会影响其他child实例工作。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
const cluster = require("cluster"); if(cluster.isMaster){
 cluster.fork();    cluster.fork();      cluster.fork();        cluster.fork(); }else{
 const express = require('express');  const app = express();  function doWork(duration){
   const start = Date.now();    while(Date.now()-start
{
   doWork(5000);    res.send("i like jonson")  })  app.get('/fast',(req,res)=>{
   res.send("i like jonson")  })  app.listen(3000); }

cluster缺陷

并不是cluster创建的child实数越多越好。因为cluster会让所有的请求都同时的结束。

想象一下我们fork了6个child,当6个请求来的时候,如果计算机没有这个处理能力,只能处理两个线程,但是6个请求又必须同时的时间结束,这反而拖慢了所有的速度。
这不如两个两个的执行好!

  • 本文链接: 

  • 版权声明: 本博客所有文章除特别声明外,均采用  许可协议。转载请注明出处!

image.png