node概念

Category:

Tags:

node概念

高并发

  • 并发: 同一时间内,多个进程,通过单个cpu切换运行
  • 并行:多个cpu同时处理多个进程
  • 高并发: 系统在一定时间内处理大量请求

进程和线程

  • 进程: 一个独立的应用程序是操作系统进行资源分配的一个单位
    • 特点:动态性 并发性 独立性 结构性
  • 线程: 进程调度的最小单位
    • 优点: 容易调度 提高到并发性 开销少
  • 多线程:操作系统可以同时运行多个任务(程序)
    • 优点
      • 任务交给后台处理
      • 提升速度
      • 消耗资源少
      • ios系统应用
    • 缺点
      • 线程切换频繁导致系统变慢
      • 累计资源比较庞大
      • 容易出bug
      • 考虑线程死锁问题(合理利用线程)

node分布式

node 特性

单线程,非阻塞式异步I/O,事件驱动

  • 单线程: node中js与其他线程无法共享状态
    • 不需要关注其他线程 没有线程切换开销 不用担心死锁
    • cpu利用率不充分 无法进行大量计算
  • 异步I/O
  • 事件驱动 eventloop

node分布式架构

  • nginx:负载均衡
  • node 集群 处理业务逻辑
  • redis: 同步状态

node集群使用

  • 启动多线程

    text
    const http = require("http"); // node 单线程 // http //   .createServer((req, res) => { //     console.log("path", req.url); //     res.end("dasdas"); //   }) //   .listen(3392, () => { //     console.log("server running at http://localhost:3392/"); //   }); // 多线程 // cluster模块解决多核cpu利用率 const cluster = require("cluster"); const numCPU = require("os").cpus().length; // 内核数 if (cluster.isMaster) {  // 是主进程  for (let i = 0; i < numCPU; i++) {    cluster.fork(); // 创建新进程 }  // 崩溃重启新进程  cluster.on("exit", (...rest) => {    console.log(rest);    cluster.fork(); }); } else {  http   .createServer((req, res) => {      console.log("path", req.url);      if (req.url === "/stop") {        throw new Error("进程崩溃");     }      res.end("dasdas");   })   .listen(3392, () => {      console.log("server running at http://localhost:3392/");   }); } ​
  • 轮询调用mysql