SFN-Channel 多进程和通信模块
光使用 Node.js 自带的 cluster 模块做多进程应用是吃力的。
SFN-Channel 提供了一个简洁友好的多进程通信 API,让你可以像类似 Socket.io 那样在工作进程和主进程、工作进程和工作进程之间,方便的传递数据。
const Channel = require("sfn-channel");
if (Channel.isMaster) {
// Master process
// Create two channels listens to worker processes A and B, and keep them
// alive.
new Channel("A", true);
new Channel("B", true);
// Do logics when the channel is online.
Channel.on("online", (channel) => {
channel.on("greeting from worker", (msg) => {
console.log("Worker %s: %s", channel.id, msg);
// greet back
channel.emit("greeting from master", `Hello, worker ${channel.id}!`);
});
});
} else {
// Worker process
Channel.on("online", channel => {
channel.emit("greeting from worker", `Hi, master, I'm worker ${channel.id}!`);
channel.on("greeting from master", msg => {
console.log("Master: %s", msg);
}).on("greeting from another worker", (id, msg) => {
console.log("Worker %s: %s", id, msg);
// greet back
channel.to(id).emit("greeting back to another worker", channel.id, `Nice to meet you, worker ${id}!`);
}).on("greeting back to another worker", (id, msg) => {
console.log("Worker %s: %s", id, msg);
})
if (channel.id === "A") {
channel.to("B").emit("greeting from another worker", "A", `Hi, worker B, I'm worker A!`);
}
});
}
更多细节请访问 GitHub 页面。