I am using Node.js, Socket.io with Redisstore, a cluster of Socket.io guys and Redis.
I have a pub / sub application that only works well on one Node.js Node. But, when it comes to heavy workloads, maxes produces only one server core, since Node.js is not written for multi-core machines.
As you can see below, now I use the Cluster module from Learnboost, the same people who make Socket.io.
But when I start 4 workflows, each browser client that logs in and subscribes receives 4 copies of each message that is published to Redis. If there are three workflows, there are three copies.
I assume that I need to somehow move the redis pub / sub function to the cluster.js file.
Cluster.js
var cluster = require('./node_modules/cluster'); cluster('./app') .set('workers', 4) .use(cluster.logger('logs')) .use(cluster.stats()) .use(cluster.pidfiles('pids')) .use(cluster.cli()) .use(cluster.repl(8888)) .listen(8000);
App.js
redis = require('redis'), sys = require('sys'); var rc = redis.createClient(); var path = require('path') , connect = require('connect') , app = connect.createServer(connect.static(path.join(__dirname, '../'))); // require the new redis store var sio = require('socket.io') , RedisStore = sio.RedisStore , io = sio.listen(app); io.set('store', new RedisStore);io.sockets.on('connection', function(socket) { sys.log('ShowControl -- Socket connected: ' + socket.id); socket.on('channel', function(ch) { socket.join(ch) sys.log('ShowControl -- ' + socket.id + ' joined channel: ' + ch); }); socket.on('disconnect', function() { console.log('ShowControll -- Socket disconnected: ' + socket.id); }); }); rc.psubscribe('showcontrol_*'); rc.on('pmessage', function(pat, ch, msg) { io.sockets.in(ch).emit('show_event', msg); sys.log('ShowControl -- Publish sent to channel: ' + ch); }); // cluster compatiblity if (!module.parent) { app.listen(process.argv[2] || 8081); console.log('Listening on ', app.address()); } else { module.exports = app; }
client.html
<script src="http://localhost:8000/socket.io/socket.io.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> <script> var socket = io.connect('localhost:8000'); socket.emit('channel', 'showcontrol_106'); socket.on('show_event', function (msg) { console.log(msg); $("body").append('<br/>' + msg); }); </script>