我刚刚深入研究了 NodeJS,并且正在阅读如何利用所有 CPU 的内核并在所有可用资源中生成进程。
这似乎是一个非常有趣的话题,我现在正在测试它。但我argv
对集群设置中的对象键有疑问。
我正在使用此脚本启动服务器:
var path = require("path"),
colors = require("colors");
var cluster = require('cluster'),
os = require('os'),
cores = os.cpus();
/*
var config = require(path.join(__dirname, 'config.json'));
*/
/*
* Start Server
*/
cluster.setupMaster({
exec : path.join(__dirname, "application.js"),
args : ["--environment", "dev"]
});
if (cluster.isMaster) {
for (var i = cores.length - 1; i >= 0; i--) {
cluster.fork();
};
cluster.on("fork", function(worker) {
console.log("Worker : [ %d ][ Status : Forking ]".cyan, worker.process.pid);
});
cluster.on("online", function(worker) {
console.log("Worker : [ %d ][ Status : Online ]".green, worker.process.pid);
});
cluster.on("listening", function(worker, address) {
console.log("Worker : [ %d ][ Status : Listening ][ Address : %s ][ Port : %d ]".yellow, worker.process.pid, address.address, address.port);
});
cluster.on("disconnect", function(worker) {
console.log("Worker : [ %d ][ Status : Disconnected ]".white, worker.process.pid);
});
/*
* Restart Dead Workers
*/
cluster.on("exit", function(worker, code, signal) {
console.log("Worker : [ %d ][ Status : Exit ][ Signal : %s ][ Code : %s ]".red, worker.process.pid, signal, code);
cluster.fork();
});
} else {
};
以上将是我的server.js
,当运行时,如 中所述exec
,启动应用程序:
var express = require("express"),
http = require('http'),
path = require("path"),
optimist = require("optimist"),
colors = require("colors"),
recess = require("recess");
var application = module.exports = express(),
config = optimist.argv;
console.log(config);
var routes = require(path.join(__dirname, "routes")),
api = require(path.join(__dirname, "routes", "api"));
application.set('view engine', 'jade');
application.set('views', path.join(__dirname, 'views'));
application.configure(function(){
application.use(express.bodyParser());
application.use(express.methodOverride());
application.use("/assets", express.static(path.join(__dirname, "public")));
application.use(express.logger('dev'));
application.use(application.router);
});
application.configure('development', function(){
application.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
application.configure('production', function(){
application.use(express.errorHandler());
});
/*
* JSON API
*/
application.get('/api/test', api.test);
/*
* Routing
*/
application.get('/', routes.index);
application.get('/partials/:name', routes.partials);
application.get('*', routes.index);
/*
* Start Server
*/
var server = http.createServer(application).listen(process.env.PORT);
那么首先,我可以使用argv
将对象作为选项发送到application.js
脚本吗?如果有怎么办?如果不是,我想我只能像现在这样发送简单的选项。
其次,最后,我的语法正确吗?是否有必要在if(cluster.isMaster) {} else {}
(如果有什么需要的话,我最感兴趣)中还有其他东西else
?如果这个问题看起来有点愚蠢,我很抱歉,但我几天前才刚刚开始,我非常渴望了解更多关于 Node 的信息 :)