一、快速实现HTTPS
1.利用OpenSSL生成证书
进入项目根目录,使用以下命令行:
~ openssl genrsa -out privatekey.pem 1024
~ openssl req -new -key privatekey.pem -out certrequest.csr
~ openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
生成3个新文件:privatekey.pem以及certificate.pem以及certrequest.csr, 证书即保存在里面。
2.利用NodeJS的HTTPS模块
server.js也很简单:
var https = require('https')
,fs = require("fs");
var options = {
key: fs.readFileSync('./privatekey.pem'),
cert: fs.readFileSync('./certificate.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world, nice to use ssl! \n");
}).listen(8000);
运行
node server.js之后就可以访问了:
二、利用Master+Worker实现简易集群
1.手动创建子进程
大概思路: 利用句柄,将同一个server对象发送给多个子进程,以实现多个进程监听同一个端口。
需要考虑到:负载均衡、子进程失败后重启、限量重启、给长连接的断开设置一个最长时间等。
(代码中只考虑了子进程失败后重启)
// master.js
var fork = require('child_process').fork;
var cpus = require('os').cpus();
var server = require('net').createServer();
server.listen(1337);
var workers = {};
var createWorker = function () {
var worker = fork(__dirname + '/worker.js');
// 退出时重新启动新的进程
worker.on('message', function (message) {
if (message.act === 'suicide') {createWorker ();
}});
worker.on('exit', function () {
console.log('Worker ' + worker.pid + ' exited.');
delete workers[worker.pid];
createWorker();
});
// 句柄转发
worker.send('server', server);
workers[worker.pid] = worker;
console.log('Create worker. pid: ' + worker.pid);
};
for (var i = 0; i < cpus.length; i++) {
createWorker();
}
// 进程自己退出时,让所有工作进程退出
process.on('exit', function () {
for (var pid in workers) {
workers[pid].kill();
}
});
// worker.js
var http = require('http');
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('handled by child, pid is ' + process.pid + '\n');
});
var worker;
process.on('message', function (m, tcp) {
if (m === 'server') {
worker = tcp;
worker.on('connection', function (socket) {
server.emit('connection', socket);
});
}
});
process.on('uncaughtException', function () {
// 记录日志
logger.error(err);
// 发送自杀信号
process.send({act: 'suicide'});
// 停止接收新的连接
worker.close(function () {
// 所有已有连接断开后,退出进程
process.exit(1);
});
2.直接利用NodeJS的Cluster模块
// cluster.js
var cluster = require('cluster');
cluster.setupMaster({
exec: "worker.js"
});
var cpus = require('os').cpus();
for (var i = 0; i < cpus.length; i++) {
cluster.fork();
}