初学者提个问题,Node Cluster 如何共享数据?
创建一个简单的 http 服务,目的是统计请求数,该例子中 fork 4 个进程,如下:
var http = require('http')
var cluster = require('cluster')
var pv = 0
if (cluster.isMaster) {
for (var i = 0; i < 4; i++) {
var worker = cluster.fork()
}
} else {
http.createServer((req, res) => {
pv++
console.log(`pid: ${process.pid}, pv: ${pv}`)
res.end('okay')
}).listen(4010)
}
结果:
pid: 70445, pv: 1
pid: 70445, pv: 2
pid: 70445, pv: 3
pid: 70445, pv: 4
pid: 70445, pv: 5
pid: 70445, pv: 6
pid: 70445, pv: 7
pid: 70445, pv: 8
pid: 70444, pv: 1
pid: 70444, pv: 2
pid: 70444, pv: 3
pid: 70444, pv: 4
pid: 70444, pv: 5
因为 fork 出来的每个进程都有自己单独的内存空间,所以这样统计 pv 显然是不行的。
所以有什么好的解决方案吗?
我看了一下 ioredis,尝试后发现它的 api 也是异步化的,并没能解决我的问题。
Cluster forks are processes, not threads. Processes are independent of each other and each has its own memory space. One process is generally not allowed to access the memory space of another process, so if you want to implement something like a shared variable The functionality of the class can only rely on process communication.
In the official documentation of the cluster module, you can actually see APIs related to process communication. You can take a look at Cluster
Of course, you can also save data to a database (such as redis) to achieve sharing, but I think it is more troublesome. . .
Write to Redis?