使用throng 运行express 应用

参考了heroku的一个demo,同时集成了perf

环境准备

  • package.json
{
  "name": "nodejs-throng",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "crypto": "^1.0.1",
    "express": "^4.17.1",
    "throng": "^5.0.0"
  }
}
 
  • app.js
const throng = require('throng')
const WORKERS = process.env.WEB_CONCURRENCY || 2
const PORT = process.env.PORT || 8080
throng(WORKERS, start)
function start(workid) {
  console.log('Starting:',workid)
  const crypto = require('crypto')
  const express = require('express')
  const app = express()
  app
    .get('/cpu', cpuBound)
    .get('/memory', memoryBound)
    .get('/io', ioBound)
    .get('/', hello)
    .listen(PORT, onListen)
  function hello(req, res, next) {
    console.log('workid:',workid)
    res.send('Hello, world')
  }
  function cpuBound(req, res, next) {
    console.log('workid:',workid)
    const key = Math.random() < 0.5 ? 'ninjaturtles' : 'powerrangers'
    const hmac = crypto.createHmac('sha512WithRSAEncryption', key)
    const date = Date.now() + ''
    hmac.setEncoding('base64')
    hmac.end(date, () => res.send('A hashed date for you! ' + hmac.read()))
  }
  function memoryBound(req, res, next) {
    console.log('workid:',workid)
    const large = Buffer.alloc(10 * 1024 * 1024, 'X')
    setTimeout(() => {
      const len = large.length  // close over the Buffer for 1s to try to foil V8's optimizations and bloat memory
      console.log(len)
    }, 1000).unref()
    res.send('Allocated 10 MB buffer')
  }
  function ioBound(req, res, next) {
    console.log('workid:',workid)
    setTimeout(function SimulateDb() {
      res.send('Got response from fake db!')
    }, 300).unref()
  }
  function onListen() {
    console.log('Listening on', PORT)
  }
}

perf

perf record -e cycles:u -g -- node --perf-basic-prof --perf-prof-unwinding-info app.js

火焰图

可以使用flamescope

运行的多进程效果

说明

最好的对比就是通过不同模式的对比火焰图

参考资料

https://github.com/rongfengliang/throng-express-perf
https://github.com/hunterloftis/throng 
https://github.com/pioardi/poolifier 
https://cube.dev/blog/jobber-runs-on-cubejs/ 
https://devcenter.heroku.com/articles/node-concurrency
https://github.com/godaddy/node-cluster-service
https://github.com/ql-io/cluster2
https://medium.com/tech-tajawal/clustering-in-nodejs-utilizing-multiple-processor-cores-75d78aeb0f4f
https://medium.com/yld-blog/cpu-and-i-o-performance-diagnostics-in-node-js-c85ea71738eb

原文地址:https://www.cnblogs.com/rongfengliang/p/14216046.html