Reputation: 277
I'm working on chat application using NodeJS and Redis , why i'm using Redis subscribe , because i need to notify other users when i user logged in , my problem start when the user logged for the first time it works fine the on message listener called for one time , but when the same user refresh the page , i found that the publish method has been called twice.
Here's sample of my code that i use:
var redisClient = redis.createClient({
auth_pass: password
});
var myServer;
myServer = require('http').createServer(app);
var socketIo = require('socket.io').listen(myServer);
myServer.listen(port);
redisClient.subscribe('myChannel');
socketIo.on('connection', function(dbSocket) {
var redisClient2 = redis.createClient({
auth_pass: password
});
/***Code for handle request***/
}
redisClient.on('message', function(channel, message) {
//When refresh page , and I call publish method , the system enter message listener twice
var data = JSON.parse(message);
});
Upvotes: 1
Views: 2752
Reputation: 769
It is because your redisClient.on('message') event is set inside the callback of on connection, therefore every time a connection is made, you attach the event again.
Move this code block outside of the on('connection') event should solve the issue.
redisClient.on('message', function(channel, message) {
//When refresh page , and I call publish method , the system enter message listener twice
var data = JSON.parse(message);
});
Upvotes: 2