[ACCEPTED]-How to reuse redis connection in socket.io?-socket.io

Accepted answer
Score: 63

Actually you are only creating a new redis 6 client for every connection if you are instantiating 5 the client on the "connection" event. What 4 I prefer to do when creating a chat system 3 is to create three redis clients. One for 2 publishing, subscribing, and one for storing 1 values into redis.

for example:

var socketio = require("socket.io")
var redis = require("redis")

// redis clients
var store = redis.createClient()
var pub = redis.createClient()
var sub = redis.createClient()

// ... application paths go here

var socket = socketio.listen(app)

sub.subscribe("chat")

socket.on("connection", function(client){
  client.send("welcome!")

  client.on("message", function(text){
    store.incr("messageNextId", function(e, id){
      store.hmset("messages:" + id, { uid: client.sessionId, text: text }, function(e, r){
        pub.publish("chat", "messages:" + id)
      })
    })
  })

  client.on("disconnect", function(){
    client.broadcast(client.sessionId + " disconnected")
  })

  sub.on("message", function(pattern, key){
    store.hgetall(key, function(e, obj){
      client.send(obj.uid + ": " + obj.text)
    })
  })

})
Score: 2

Redis is optimized for a high level of concurrent connections. There is also discussion about multiple 10 database connections and connection pool 9 implementation in node_redis module.

Is it possible 8 to reuse redis connection if the cookies 7 are same? So if someone open many browser 6 tabs also treat as open 1 connection.

You 5 can use for example HTML5 storage on the client side 4 to keep actively connected only one tab 3 and others will handle communication/messages 2 through storage events. It's related to 1 this question.

Score: 1

I had this exact problem, with an extra 8 requirement that clients must be able to 7 subscribe to private channels, and publish 6 to those channels should not be sent to 5 all listeners. I have attempted to solve 4 this problem by writing a miniature plugin. The 3 plugin:

  • Uses only 2 redis connections, one for pub, one for sub
  • Only subscribes to "message" once total (not once every redis connection)
  • Allow clients to subscribe to their own private channels, without messages being sent to all other listening clients.

Especially useful if your prototyping 2 in a place where you have a redis connection 1 limit (such as redis-to-go). SO link: https://stackoverflow.com/a/16770510/685404

Score: 1

You need to remove the listener when client 1 disconnect.

var io = io.listen(server),
    buffer = [];

var redis = require("redis");

var subscribe = redis.createClient();  

io.on('connection', function(client) {

    console.log(client.request.headers.cookie);

    subscribe.get("..", function (err, replies) {

    });

    var redis_handler = function(channel,message) {

        var msg = { message: [client.sessionId, message] };
        buffer.push(msg);
        if (buffer.length > 15) buffer.shift();
        client.send(msg);
    };

    subscribe.on("message", redis_handler);


    client.on('message', function(message){
    });

    client.on('disconnect', function(){
        subscribe.removeListerner('message', redis_handler)
        //subscribe.quit();
    });
});

See Redis, Node.js, and Socket.io : Cross server authentication and node.js understanding

Score: 0

Using redis as a store has become much simpler 12 since this question was asked/answered. It is built in now.

Note, that 11 if you are using redis because you are using 10 the new node clustering capabilities (utilizing 9 multiple CPUs), you have to create the server 8 and attach the listeners inside of each 7 of the cluster forks (this is never actually 6 explained anywhere in any of the documentation 5 ;) ). The only good code example online 4 that I have found is written in CoffeeScript 3 and I see a lot of people saying this type 2 of thing "just doesn't work", and 1 it definitely doesn't if you do it wrong. Here's an example of "doing it right" (but it is in CoffeeScript)

More Related questions