Skip to content

Instantly share code, notes, and snippets.

@yeukhon
Last active August 29, 2015 14:04
Show Gist options
  • Save yeukhon/9a5ef85b091287a48552 to your computer and use it in GitHub Desktop.
Save yeukhon/9a5ef85b091287a48552 to your computer and use it in GitHub Desktop.
Simple example of pub/sub using node.js and redis client
// Usage:
// node pub.js
// then starts typing message (ENTER per message)
// A publisher could be invokved by a background job
// processor or a user triggered action received by
// web app.
var redis = require("redis");
var pub = redis.createClient();
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (input) {
pub.publish("latest",
JSON.stringify(
{
"msg": input.trim(), // remove whitespaces and \n
"time": new Date().toJSON()
}
)
);
});
var redis = require('redis');
var sub = redis.createClient();
// Listens on "latest" channel
// when we receive a message, log it.
// In real world, you would use this in a web server application
// and sends the message to browser client.
// (or do whatever you want here, e.g. writing to log file)
sub.subscribe("latest");
sub.on("message", function (channel, message) {
console.log("subscriber:", message);
});
@yeukhon
Copy link
Author

yeukhon commented Jul 28, 2014

vagrant@precise64:/tmp$ node sub.js
subscriber:
'{"msg":"next\\n","time":"2014-07-28T01:05:23.929Z"}'
subscriber:
'{"msg":"werwrew\\n","time":"2014-07-28T01:05:26.229Z"}'
subscriber:
'{"msg":"asasa","time":"2014-07-28T01:06:07.792Z"}'
subscriber:
'{"msg":"sasasa","time":"2014-07-28T01:06:10.267Z"}'

You can also use monitor in your redis-cli to monitor redis activity.

1406509521.116490 [0 127.0.0.1:45128] "subscribe" "latest"
1406509523.930096 [0 127.0.0.1:45127] "publish" "latest" "{\"msg\":\"next\\n\",\"time\":\"2014-07-28T01:05:23.929Z\"}"
1406509526.229292 [0 127.0.0.1:45127] "publish" "latest" "{\"msg\":\"werwrew\\n\",\"time\":\"2014-07-28T01:05:26.229Z\"}"
1406509566.552345 [0 127.0.0.1:45129] "info"
1406509567.793315 [0 127.0.0.1:45129] "publish" "latest" "{\"msg\":\"asasa\",\"time\":\"2014-07-28T01:06:07.792Z\"}"
1406509570.267953 [0 127.0.0.1:45129] "publish" "latest" "{\"msg\":\"sasasa\",\"time\":\"2014-07-28T01:06:10.267Z\"}"
1406509615.807409 [0 127.0.0.1:45130] "info"
1406509615.812043 [0 127.0.0.1:45130] "subscribe" "latest"
1406509617.838549 [0 127.0.0.1:45131] "info"
1406509618.268611 [0 127.0.0.1:45131] "publish" "latest" "{\"msg\":\"a\",\"time\":\"2014-07-28T01:06:58.267Z\"}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment