2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Redis] publish、subscribeを行う

2
Posted at

node.js上でredisを使ってpublish、subscribeを行う方法を記載。

もろもろはいっている前提、

redis = {};
redis.pub  = function(){
    var sys        = require('sys');
    var redis      = require('redis');
    var subscriber = redis.createClient(6379, 'localhost');

    subscriber.subscribe('hoge channel');
    subscriber.on("message", function(channel, message) {
        sys.puts(channel + " :" + message);
    });

    publisher = redis.createClient(6379, 'localhost');
    publisher.publish("hoge channel", "test message");
};

redis.sub = function(){
    var sys        = require('sys');
    var redis      = require('redis');
    var subscriber = redis.createClient(6379, 'localhost');

     subscriber.subscribe('hoge channel');
     subscriber.on("message", function(channel, message) {
        sys.puts(channel + " :" + message);
     });
};

node.jsがpubの場合は、ターミナルで事前に以下のコマンドを叩いておくと、publishされた情報が表示されます。

redis-cli subscribe "hoge channel"

逆に、node.js側がsubscribeの場合は
ターミナルでpublishするとnode.js
側でメッセージが表示されます。

redis-cli publish "hoge channel" "Hello World"

以上

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?