拥有 node.js 快速应用程序的网络工作者

Webworkers with a node.js express application

我是 node.js 的新手,正在尝试构建一个快速应用程序。 到目前为止,我已经设置了一个应用程序并创建了一些基本路线。

我的应用程序入口点是一个文件,我在其中设置应用程序的服务器:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('main');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

Express 应用程序使用猫鼬在适当的 http 请求上与数据库通信。

在这一点上,我还需要一个网络工作者,当服务器启动时,每5秒生成一次随机数,如果生成的数字是10,则将其标识为一个事件,并将一些结果存储在数据库中.

到目前为止,我不确定如何开始并将其包含在结构中。

我已经设置了用于写入数据库等的接口。我只是迷失了 web-worker 实现和集成部分。

在node.js中没有网络工作者。但是我们有类似的东西叫做 child_process(请查看文档了解更多详情:link

如何使用child_process? Whosebug里面有很多资料: 在主模块 运行 其他模块中有解释(查看那里的详细信息): 在您的主模块中:

var cp = require('child_process');
var child = cp.fork('./othermodulefile');

child.on('message', function(m) {
  // Receive results from child process
  console.log('received: ' + m);
});

// Send child process some work
child.send('Please up-case this string');

或者请看这个 link 上瘾的描述 http://www.tutorialspoint.com/nodejs/nodejs_scaling_application.htm 以及该页面的示例: 文件:support.js

console.log("Child Process " + process.argv[2] + " executed." );

文件:master.js

const fs = require('fs');
const child_process = require('child_process');

for(var i=0; i<3; i++) {
   var workerProcess = child_process.exec('node support.js '+i,
      function (error, stdout, stderr) {
         if (error) {
            console.log(error.stack);
            console.log('Error code: '+error.code);
            console.log('Signal received: '+error.signal);
         }
         console.log('stdout: ' + stdout);
         console.log('stderr: ' + stderr);
      });

      workerProcess.on('exit', function (code) {
      console.log('Child process exited with exit code '+code);
   });
}

使用 child_process 的一些缺点:

Each thread cost memory, and this is generally why most of traditional systems is not much scalable as will require thread per client. For node it will be extremely inefficient from hardware resources point of view.

其他部分:

Count of workers is recommended to be equal of CPU Cores on hardware.

其他可能性,如果您需要 运行 一些基于时间的作业调度程序,请查看此模块 https://github.com/ncb000gt/node-cron。这是 node.js 定时任务。安装 npm install cron 和使用示例:

var CronJob = require('cron').CronJob;
new CronJob('* * * * * *', function() {
  console.log('You will see this message every second');
}, null, true, 'America/Los_Angeles');