node.js study: cluster
2016-03-22 21:19
519 查看
从v0.6.x开始,Node.js提供了多进程模块cluster,允许创建一组进程来共享同一个socket,并且分担负载压力。
官方文档是这样说的:
A single instance of Node.js runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node.js processes to handle the load.
The cluster module allows you to easily create child processes that all share server ports.
单个node.js实例的运行是单线程的。用户有时候想运行一组进程来运行node.js实例以提高多核系统的性能。
cluster模块让你轻松创建可以共享服务端口的子进程。
那么试试先,用cluster共享一个http服务。
cluster-1.js:
开启服务:
http访问效果:
显然,虽然每次http访问都能得到结果“hello world”,但却并不是同一个进程。
并且我们可以看到cluster实现了的负载均衡,cluster会把请求依次分配给子进程2-3-1-4-2-3-1-4...........这是一个罗宾环。
cluster默认使用round-robin来实现负载均衡。也可以不使用round-robin。
这个时候,http访问的效果变成了随机:
cluster是如何工作的?
cluster的工作进程是通过child_process.fork()来创建的,所以它们与父进程间可以进行通讯。
可以从源码中找到child_process.fork()的实现。
源码片段:
转载链接:http://helloweb.wang/qianduankaifa/496.html
官方文档是这样说的:
A single instance of Node.js runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node.js processes to handle the load.
The cluster module allows you to easily create child processes that all share server ports.
单个node.js实例的运行是单线程的。用户有时候想运行一组进程来运行node.js实例以提高多核系统的性能。
cluster模块让你轻松创建可以共享服务端口的子进程。
那么试试先,用cluster共享一个http服务。
cluster-1.js:
开启服务:
http访问效果:
显然,虽然每次http访问都能得到结果“hello world”,但却并不是同一个进程。
并且我们可以看到cluster实现了的负载均衡,cluster会把请求依次分配给子进程2-3-1-4-2-3-1-4...........这是一个罗宾环。
cluster默认使用round-robin来实现负载均衡。也可以不使用round-robin。
这个时候,http访问的效果变成了随机:
cluster是如何工作的?
cluster的工作进程是通过child_process.fork()来创建的,所以它们与父进程间可以进行通讯。
可以从源码中找到child_process.fork()的实现。
源码片段:
转载链接:http://helloweb.wang/qianduankaifa/496.html
相关文章推荐
- Swap Nodes in Pairs
- NodeJS + PhantomJS 抓取页面信息以及截图
- 快速搭建 Node.js 开发环境以及加速 npm
- Node.js文件操作二
- nodejs+express开发blog(2)
- node.js 异步I/O
- NodeJS - Error: The specified procedure could not be found
- Leetcode 19. Remove Nth Node From End of List
- node.js小工具--修改Xcode 'Create by'作者名称
- node.js 调试
- nodejs+express开发blog(1)
- Nodejs学习笔记(十三)— PM2
- hadoop启动报错-namenode无法启动-GC overhead limit exceeded
- NoNodeAvailableException[None of the configured nodes are available
- 安装node.js 及安装gulp步骤
- windows下搭建node.js及npm的工作环境
- Leetcode #19. Remove Nth Node From End of List 移除倒数第N个链表节点 解题小节
- node.js之回调函数示例
- DOM中所有节点类型(nodeType);(读书笔记)
- 222. Count Complete Tree Nodes