# 写在前面
下文适合对cluster模块有一定了解的同学阅读。主要包含两部分内容:
- cluster模块如何实现端口共享
- cluster模块如何分发请求
# 端口共享源码分析
首先,master 进程 fork() 子进程:
// master进程
cluster.fork()
@前端进阶之旅: 代码已经复制到剪贴板
子进程创建 net.Server 实例:
// worker进程
require('net').createServer(() => {}).listen(3000);
@前端进阶之旅: 代码已经复制到剪贴板
在 net 模块中,调用 cluster._getServer
// worker进程
cluster._getServer(self, {
address: address,
port: port,
addressType: addressType,
fd: fd,
flags: 0
}, cb);
function cb(err, handle) {
// 忽略错误处理
self._handle = handle;
self._listen2(address, port, addressType, backlog, fd);
}
@前端进阶之旅: 代码已经复制到剪贴板
在 cluster._getServer 中,通过 process.send(message),向 master 进程发送 queryServer 请求。
// worker进程
cluster._getServer = function(obj, options, cb) {
const indexesKey = [ options.address,
options.port,
options.addressType,
options.fd ].join(':');
if (indexes[indexesKey] === undefined)
indexes[indexesKey] = 0;
else
indexes[indexesKey]++;
// message =>
// {
// act: 'queryServer',
// index: ':3000:4:',
// data: null,
// address: null,
// port: 3000,
// addressType: 4,
// fd: undefined