Vietnam

    Nodejs.vn

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Popular
    • Tags
    • Groups
    • Search

    [Cluster] Thắc mắc về cluster

    Tutorials
    0
    2
    1344
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • vahaha
      vahaha last edited by vahaha

      Mình đang tìm hiểu về cluster có đoạn mã như bên dưới.
      Đơn giản là tạo ra 4 worker, trong mỗi worker thì chạy đoạn mã nghe cổng 8000. Mỗi khi có request thì in ra console và response process id của worker xử lý.

      Điều hơi khó hiểu là mỗi lần tạo request thì console in ra 2 lần process id. Tại sao vậy nhỉ?

      var cluster = require('cluster');
      var http = require('http');
      var numCPUs = 4;
      
      if (cluster.isMaster) {
          for (var i = 0; i < numCPUs; i++) {// tao worker
              cluster.fork();
          }
      } else {
          // tao server
          http.createServer(function(req, res) {
              console.log(process.pid); // in ra process id dang xu ly
              res.writeHead(200);
              res.end('process ' + process.pid + ' says hello!');
          }).
      }
      
      • . ^
      1 Reply Last reply Reply Quote 0
      • vahaha
        vahaha last edited by

        Mình đã tìm đc câu trả lời. Nguyên nhân là do mình dùng trình duyệt để tạo request. Mặc định trình duyệt sẽ tạo ra 2 request (http://localhost:8000/ và http://localhost:8000/favicon.ico). Vậy nên, server sẽ in ra 2 lần process id.
        Nếu test với một ứng dụng test api (ví dụ Boomerang) thì process id chỉ được in ra 1 lần (do chỉ có 1 request được gửi đến server).

        • . ^
        1 Reply Last reply Reply Quote 2
        • First post
          Last post