SFN-Channel 多进程和通信模块
发布于 7 年前 作者 Hyurl 3507 次浏览 来自 分享

光使用 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 页面。

5 回复

并没有共享内存

来自酷炫的 CNodeMD

@zswnew 共享内存的叫线程

@Hyurl 共享内存可以用系统机制来做···········之前有个人用c++ 做出来了~~~ 多进程共享同一块内存

@ipengyo Buffer好像可以在c++扩展和js之间共享样

来自酷炫的 CNodeMD

回到顶部