1. const cluster = require('cluster')
    2. const http = require('http')
    3. const { cpus } = require('os')
    4. const numCPUs = cpus().length
    5. if (cluster.isPrimary) {
    6. console.log(`Primary ${process.pid} is running`)
    7. // Fork workers.
    8. for (let i = 0; i < numCPUs; i++) {
    9. cluster.fork()
    10. }
    11. cluster.on('exit', (worker, code, signal) => {
    12. console.log(`worker ${worker.process.pid} died`)
    13. })
    14. } else {
    15. // Workers can share any TCP connection
    16. // In this case it is an HTTP server
    17. http.createServer((req, res) => {
    18. res.writeHead(200)
    19. res.end('hello world\n')
    20. }).listen(8000)
    21. console.log(`Worker ${process.pid} started`)
    22. }
    23. /* 会自动重新执行自身
    24. Primary 25020 is running
    25. Worker 25021 started
    26. Worker 25022 started
    27. Worker 25024 started
    28. Worker 25023 started
    29. Worker 25025 started
    30. Worker 25027 started
    31. Worker 25026 started
    32. */
    1. const cluster = require('cluster')
    2. const http = require('http')
    3. const { cpus } = require('os')
    4. if (cluster.isPrimary) {
    5. // Keep track of http requests
    6. let numReqs = 0
    7. setInterval(() => {
    8. console.log(`numReqs = ${numReqs}`)
    9. }, 1000)
    10. // Count requests
    11. function messageHandler (msg) {
    12. if (msg.cmd && msg.cmd === 'notifyRequest') {
    13. numReqs += 1
    14. }
    15. }
    16. // Start workers and listen for messages containing notifyRequest
    17. const numCPUs = cpus().length
    18. for (let i = 0; i < numCPUs; i++) {
    19. cluster.fork()
    20. }
    21. for (const id in cluster.workers) {
    22. cluster.workers[id].on('message', messageHandler)
    23. }
    24. } else {
    25. // Worker processes have a http server.
    26. http.Server((req, res) => {
    27. res.writeHead(200)
    28. const pid = process.pid
    29. res.end('process.pid' + pid)
    30. // Notify primary about the request
    31. process.send({ cmd: 'notifyRequest' })
    32. }).listen(3000)
    33. }