Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pop objects from Redis as they are added realtime?

Tags:

node.js

redis

I want to get a Node.js process running as it's checking a Redis server for anything new to pop.

Another process will be doing the pushing sporadically, and the Node process will be trying to pop whatever that comes in. The Node process will stay running.

Can anyone point me to a good direction?

I'm trying to figure out how to listen for such event. Sure, I can pop it once, but how do I get Node process to keep listening for any addition to Redis server?

like image 331
deeJ Avatar asked Mar 24 '13 19:03

deeJ


People also ask

How does Redis integrate with node js?

Create new session. js file in the root directory with the following content: const express = require('express'); const session = require('express-session'); const redis = require('redis'); const client = redis. createClient(); const redisStore = require('connect-redis')(session); const app = express(); app.

Which method of the client object is used to execute a set of commands atomically using the node Redis driver?

execAsync( ) the execution of the query will happen atomically.


2 Answers

You'll want to use a blocking pop: http://redis.io/commands/brpop

function waitForPush () {
  client.brpop(['list','otherlist',0], function (listName, item) {
    // do stuff
    waitForPush();
  });
}
like image 139
generalhenry Avatar answered Sep 19 '22 06:09

generalhenry


This seems like a good use case for pub/sub: http://redis.io/topics/pubsub

Your Node.js process that sporadically pushes to Redis can also publish to a channel each time it pushes something. Like this:

var pushClient = redis.createClient();
//push something onto Redis
pushClient.publish("pubsub-channel", "Just pushed something onto Redis");

Then your other process would subscribe to that channel. Each time the message event is fired, you pop off whatever was just pushed:

var client = redis.createClient();
client.subscribe("pubsub-channel");
client.on("message", function(channel, message){
//pop off new item
});
like image 45
Mike Avatar answered Sep 20 '22 06:09

Mike