我尝试了以下服务器+工作人员代码,但它根本无效。
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:
process.on('message', function(obj) {
//Will add more code to it later...
console.log("CHILD::Received: ",obj);
});
在儿童流程中给我以下错误'的console.log():
JSON.stringify, avoid TypeError: Converting circular structure to JSON
有什么建议吗?
答案 0 :(得分:1)
我这样做的方法是让worker.js成为真正的“app”,server.js只是设置集群。我没有对此进行过测试,但有些事情就是这样:
// 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');
}
对于奖励积分,您可以使用类似节点池的内容来创建连接池,并让db模块从池中返回连接。