如何跨节点集群共享一个资源
How can I share one resource across Node clusters
我正在使用节点 cluster
模块,每个 worker 加载一个数据库连接。
index.js
const cluster = require('cluster');
const database = require('./db.js');
if (cluster.isMaster) {
cluster.fork();
cluster.fork();
} else {...}
db.js
const mysql = require('mysql');
const pool = new mysql.pool(config);
module.exports = function(query){
return pool.query(query);
}
我的理解是,每次生成一个worker,它都会初始化db.js
,这会创建一个新的pool/connections到mysql。
是否有另一种方法来构造它,以便所有工作人员共享同一个 mysql 池?
无法在 Node.js worker 和 master 之间共享资源。其中每一个都是一个新进程,您所能做的就是通过消息进行通信(文档 here)。
基于 Node.js 文档:
The worker processes are spawned using the child_process.fork() method, so that they can communicate with the parent via IPC and pass server handles back and forth.
对于每个 child_process
,我们有:
It is important to keep in mind that spawned Node.js child processes are independent of the parent with exception of the IPC communication channel that is established between the two. Each process has its own memory, with their own V8 instances. Because of the additional resource allocations required, spawning a large number of child Node.js processes is not recommended.
根据您的应用程序架构,您可以将要共享的资源移至主节点,然后将工作分配给工作节点。
我正在使用节点 cluster
模块,每个 worker 加载一个数据库连接。
index.js
const cluster = require('cluster');
const database = require('./db.js');
if (cluster.isMaster) {
cluster.fork();
cluster.fork();
} else {...}
db.js
const mysql = require('mysql');
const pool = new mysql.pool(config);
module.exports = function(query){
return pool.query(query);
}
我的理解是,每次生成一个worker,它都会初始化db.js
,这会创建一个新的pool/connections到mysql。
是否有另一种方法来构造它,以便所有工作人员共享同一个 mysql 池?
无法在 Node.js worker 和 master 之间共享资源。其中每一个都是一个新进程,您所能做的就是通过消息进行通信(文档 here)。
基于 Node.js 文档:
The worker processes are spawned using the child_process.fork() method, so that they can communicate with the parent via IPC and pass server handles back and forth.
对于每个 child_process
,我们有:
It is important to keep in mind that spawned Node.js child processes are independent of the parent with exception of the IPC communication channel that is established between the two. Each process has its own memory, with their own V8 instances. Because of the additional resource allocations required, spawning a large number of child Node.js processes is not recommended.
根据您的应用程序架构,您可以将要共享的资源移至主节点,然后将工作分配给工作节点。