【发布时间】:2019-03-25 06:15:24
【问题描述】:
我想知道在使用cluster 模块扩展我的Node.JS 应用程序时如何正确使用MySQL。目前,我只提出了两个解决方案:
解决方案 1:
在每个“worker”上创建一个数据库连接。
解决方案 2:
在主进程上建立数据库连接,每当其中一个工作人员请求一些数据时,主进程都会返回数据。但是,使用此解决方案,我不知道如何让工作人员从主进程中检索数据。
我(认为)我做了一个“hacky”解决方法,发出一个唯一编号,然后等待主进程将消息发送回工作人员,事件名称是唯一编号。
如果你不明白我的意思,这里有一些代码:
// Worker process
return new Promise (function (resolve, reject) {
process.send({
// Other data here
identifier: <unique number>
})
// having a custom event emitter on the worker
worker.once(<unique number>, function (data) {
// data being the data for the request with the unique number
// resolving the promise with returned data
resolve(data)
})
})
//////////////////////////
// Master process
// Custom event emitter on the master process
master.on(<eventName>, function (data) {
// logic
// Sending data back to worker
master.send(<other args>, data.identifier)
}
解决这个问题的最佳方法是什么?
感谢您的阅读。
【问题讨论】:
-
你为什么不喜欢解决方案 1?
-
我在 Discord 上问过某人,他说:“在主线程上肯定有 db 访问权限,这将控制数据流,否则你会有有趣的数据竞争和其他未定义的行为”
标签: node.js node-cluster