pub_sub.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var redis = require("redis"),
  2. client1 = redis.createClient(), msg_count = 0,
  3. client2 = redis.createClient();
  4. redis.debug_mode = false;
  5. // Most clients probably don't do much on "subscribe". This example uses it to coordinate things within one program.
  6. client1.on("subscribe", function (channel, count) {
  7. console.log("client1 subscribed to " + channel + ", " + count + " total subscriptions");
  8. if (count === 2) {
  9. client2.publish("a nice channel", "I am sending a message.");
  10. client2.publish("another one", "I am sending a second message.");
  11. client2.publish("a nice channel", "I am sending my last message.");
  12. }
  13. });
  14. client1.on("unsubscribe", function (channel, count) {
  15. console.log("client1 unsubscribed from " + channel + ", " + count + " total subscriptions");
  16. if (count === 0) {
  17. client2.end();
  18. client1.end();
  19. }
  20. });
  21. client1.on("message", function (channel, message) {
  22. console.log("client1 channel " + channel + ": " + message);
  23. msg_count += 1;
  24. if (msg_count === 3) {
  25. client1.unsubscribe();
  26. }
  27. });
  28. client1.on("ready", function () {
  29. // if you need auth, do it here
  30. client1.incr("did a thing");
  31. client1.subscribe("a nice channel", "another one");
  32. });
  33. client2.on("ready", function () {
  34. // if you need auth, do it here
  35. });