node http.createServer用了cluster模块后,RPS没有明显变化?
发布于 3 个月前 作者 L-Chris 543 次浏览 来自 问答

本人新手,参考网上资料,写了2个例子,并在centos环境下用segie测试负载均衡

最终得到的结果是各项参数都几乎一样,没任何差别,有人解释下吗

node: 12.3.1 centos: 7 64bit

代码如下

// http.js
const http = require('http')

http.createServer((req, res) => {
  res.end(`Hello World!`)
}).listen(3000)
// http-cluster.js
const cluster = require('cluster')
const http = require('http')
const cpuCount = require('os').cpus().length

if (cluster.isMaster) {
  console.log('[master] start master...')

  for (let i = 0; i < cpuCount; i++) {
    cluster.fork()
  }

  cluster.on('listening', (worker, address) => {
    console.log(`[master] listening: worker-${worker.id}, pid:${worker.process.pid}, Address:${address.address || '0.0.0.0'}:${address.port}`)
  })
} else if (cluster.isWorker) {
  console.log(`[workder] start worker ... ${cluster.worker.id}`)

  http.createServer((req, res) => {
    res.end('Hello World!')
  }).listen(3000)
}
1 回复
package main
import (
    "fmt"
	"runtime"
    "net/http"
)
func IndexHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "hello world")
}
func main() {
  //  runtime.GOMAXPROCS(runtime.NumCPU())
http.HandleFunc("/", IndexHandler)
http.ListenAndServe("127.0.0.1:8000",nil)
}

maxprocs.png 多核要为cpu调度和上下文切换付出更多的时间

回到顶部