下面是我写的一段代码,但是没有用。有了这段代码-如何重构它以实现多线程或集群,以便可以利用cpus的数量从而提高应用程序的性能?
if (cluster.isMaster) {
console.log('Master ${process.pid} is running');
for (let i = 0; i < numOfCpus; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log('worker ${worker.process.pid} died');
});
} else {
db.sequelize.sync({
force: false
}).then(function () {
app.listen(PORT, function (req, res) {
res.writeHead(200);
res.end('hey');
console.log("==> Listening on port %s. Visit http://localhost:%s/ in your browser.", PORT, PORT);
});
console.log(' Worker ${process.pid} started');
});
}
答案 0 :(得分:0)
我一直在做类似的事情。我在您的评论中看到您仍然继续创建Spring Boot应用程序,但以防万一,我认为您的问题来自传递给'listen'方法的回调。您将状态200写入响应标头,然后以res.end('hey');
也许您只是调用'listen'方法并随后使用server.on('listening')
方法处理任何其他逻辑,它将解决您的问题吗?当我在应用程序上对其进行测试时,它似乎可以工作。到目前为止,这是我的bin / www,其中app
是快速应用程序,db
是Sequelize模型:
#!/usr/bin/env node
/**
* Module dependencies.
*/
const http = require('http');
const cluster = require('cluster');
const os = require('os');
const config = require('../server/config')[process.env.NODE_ENV || 'development'];
const app = require('../server/app')(config);
const db = require('../server/models');
const log = config.log();
const numCPUs = os.cpus().length;
// Helper functions
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
const port = parseInt(val, 10);
if (Number.isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server and listen on the provided port
*/
const server = http.createServer(app);
if (cluster.isMaster) {
log.info(`Master ${process.pid} is running`);
for (let i = 0; i < numCPUs; i += 1) {
cluster.fork();
}
cluster.on('exit', (worker) => {
log.fatal(`Worker ${worker.process.pid} just died`);
cluster.fork();
});
} else {
db.sequelize.sync({ force: false })
.then(() => {
log.info('Connected to database');
server.listen(port);
})
.catch((err) => {
log.fatal(err);
});
}
server.on('listening', () => {
const addr = server.address();
const bind = typeof addr === 'string'
? `pipe ${addr}`
: `port ${addr.port}`;
log.info(`Listening on ${bind}`);
});
// Handle server errors
server.on('error', (error) => {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string'
? `Pipe ${port}`
: `Port ${port}`;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
log.fatal(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
log.fatal(`${bind} is already in use`);
process.exit(1);
break;
default:
log.info(error);
// throw error;
}
});