-
-
Save kurokikaze/80259cdddd0aabb6b816 to your computer and use it in GitHub Desktop.
Многопоточная обработка запросов в Ноде
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var child_process = require('child_process'), | |
netBinding = process.binding('net'), | |
http = require('http'), | |
sys = require('sys'), | |
fs = require('fs'), | |
net = require('net'); | |
var workers = 4; | |
sys.puts('Starting...'); | |
if (workers) { | |
if (process.version < '0.1.98') { | |
abort('Cannot use workers with a version older than v0.1.98'); | |
} | |
// Создаём дескриптор для передачи | |
var fd = netBinding.socket('tcp4'); | |
// Слушаем на порту 8080 | |
netBinding.bind(fd, 8080); | |
netBinding.listen(fd, 128); | |
for (var i = 0; i < workers; i++) { | |
// Создаём пару сокетов | |
var fds = netBinding.socketpair(); | |
var instance = i; | |
// Запускаем дочерний процесс | |
var child = child_process.spawn( | |
process.argv[0], | |
['worker.js', '--child'], | |
undefined, | |
[fds[1], -1, -1] | |
); | |
// Патч для пропадающего почему то stdin'а у дочернего процесса | |
if (!child.stdin) { | |
child.stdin = new net.Stream(fds[0], 'unix'); | |
} | |
// Записываем pid потомка, чтобы не потерять | |
fs.writeFileSync('/var/run/nodeworker' + i + '.pid', child.pid.toString(), 'ascii'); | |
// Передаём потомку environment и дескриптор порта | |
child.stdin.write(JSON.stringify({}), 'ascii', fd); | |
sys.puts('Worker ' + i + ' started'); | |
// Log stdout / stderr | |
(function(i) { | |
child.stdout.addListener('data', function(data) { | |
// let i = instance; | |
sys.puts('Child ' + i + 'data: ' + data); | |
}); | |
child.stderr.addListener('data', function(data) { | |
// tance; | |
sys.puts('Child ' + i + ' error: ' + data); | |
}); | |
})(instance); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'), | |
sys = require('sys'), | |
net = require('net'); | |
var stdin = new net.Stream(0, 'unix'); | |
stdin.addListener('data', function(json) { | |
// Получаем переменные окружения | |
env = JSON.parse(json.toString()); | |
}); | |
stdin.addListener('fd', function(fd){ | |
// Получаем наш файловый дескриптор | |
var app = http.createServer(function (req, res) { | |
sys.puts('Request comes'); | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
res.end('Hello World\n'); | |
}); | |
app.listenFD(fd, 'tcp4'); | |
sys.puts('Child listening'); | |
}); | |
stdin.resume(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment