简体   繁体   English

NodeJS-如何将mysql连接从主进程传递到子进程?

[英]NodeJS - How to pass a mysql connection from main to child process?

I tried the following server+worker code but it simply did not work. 我尝试了以下server + worker代码,但它根本无法正常工作。

server.js: server.js:

var net = require('net');
var mysql = require('mysql');
var cp = require('child_process');

var serverPort=20460;

var connection = mysql.createConnection({
    database : 'test',
    host     : 'localhost',
    user     : 'root',
    password : ''
});

var server = net.createServer(function (socket){
    socket.on('data',function(data){
        console.log("Server received: ",data);
        var child = cp.fork('./worker');
        child.send({'connection': connection});
    });
});

connection.connect(function(err, two){
    if (!err) {
        server.listen(serverPort);
    }
});

worker.js: worker.js:

process.on('message', function(obj) {
    //Will add more code to it later...
    console.log("CHILD::Received: ",obj);
});

Gives me the following error at the child process' console.log(): 在子进程的console.log()中给我以下错误:

JSON.stringify, avoid TypeError: Converting circular structure to JSON

Any suggestions ? 有什么建议么 ?

The way I'd do it is to have worker.js be the real "app" and the server.js just sets up the clustering. 我要做的方法是让worker.js成为真正的“应用程序”,而server.js只是设置集群。 I've not tested this, but something along the lines of this: 我尚未对此进行测试,但与此类似:

// worker.js    
var connection = require('./db');
var net = require('net');

var server = net.createServer(function (socket){
    socket.on('data',function(data){
        console.log("Server received: ",data);
        connection.connect();
        connection.query(/* your query here for inserting data */);
        connection.end();
    });
});

// db.js
var mysql = require('mysql');

var serverPort=20460;

var connection = mysql.createConnection({
    database : 'test',
    host     : 'localhost',
    user     : 'root',
    password : ''
});
module.exports = connection;

// server.js
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  require('./worker');
}

For bonus points, you could use something like node-pool to create a connection pool, and have the db module return a connection from the pool instead. 为了获得加分,您可以使用诸如node-pool之类的方法来创建连接池,并让db模块从池中返回连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM