2016-12-12 5 views
1

nodejsのredisから変更された値イベントを聴くことは可能ですか?NodeJS Redis Listener

状況: は、私は別のアプリケーション(同じサーバー上のネイティブアプリケーション、FOOそれを呼び出すと、ノード・アプリケーションバーを呼び出すことができます)からのリアルタイムデータを示しNodeJSアプリケーションを持っています。

Fooは、マシンの状態をredisキー "state"に保存します。バーがこれを登録して表示します。このイベントをどのように捕捉できますか?

Pierres Solutionはキーの取得には問題ありませんが、値を取得するにはどうすればよいですか?私はこのようにそれを試してみました、しかしParseErrorですが発生します。

var redis = require("redis"); 
var client_redis = redis.createClient(); 

client_redis.config('set', 'notify-keyspace-events', 'KEA'); 
client_redis.subscribe('[email protected]__:set'); 
client_redis.on('message', function(channel, key) { 
    client_redis.get(key, function(error, result) { 
    if (error) console.log(error); 
    else console.log(result); 
    }); 
}); 

エラー

$ { ReplyError> at parseError (/home/pi/Website/node_modules/redis-parser/lib/parser.js:181:12) -bash: syntax error near unexpected token `(' 

編集#2これは、対応する値を読むからclient_redis.subscribe('...')ブロッククライアントのように思える

キー。私は値を読み取る第2のクライアントを追加しました。

実施例:

var redis = require("redis"); 
// Client for subscription 
var subscriptionClient = redis.createClient(); 
// Client for reading the values from the keys. 
var readClient = redis.createClient(); 


subscriptionClient.config('set', 'notify-keyspace-events', 'KEA'); 
// subscribe to the key event so we get notificated if a value changes 
subscriptionClient.subscribe('[email protected]__:set'); 

subscriptionClient.on('message', function(channel, key) { 
    readClient.get(key, function(err, value) { 
    console.log(value); 
    }); 
}); 
+0

はい、あなたは二Redisのクライアントを追加する必要があります。 Redisクライアントがサブスクライバモードに入ると、それ以上のチャネルを購読したり、サブスクライブしたサブスクライブからの参加を解除する以外の操作は実行できなくなります。 –

答えて

3

はい、それは可能です。 Redis Keyspace Notificationsを使用する必要があります。

特にを参照してください。異なるコマンドの部分によって生成されたイベント。おそらくSETコマンドを使用しているときに通知することにしたい。

var redis = require('redis'); 
var client_redis = redis.createClient(); 

// enable notify-keyspace-events for all kind of events (can be refined) 
client_redis.config('set','notify-keyspace-events','KEA'); 

client_redis.subscribe('[email protected]__:set'); 
// you can target a specific key with a second parameter 
// example, client_redis.subscribe('[email protected]__:set', 'mykey') 

client_redis.on('message', function(channel, key) { 
    // do what you want when a value is updated 
}); 
+1

私は自分の答えを更新しました。 –

+0

Iveは私の質問にEdit-Partを追加しました。これまでにありがとう、魅力のようなキーの作品を見つけるが、私は私の値を取得できるようにその解析エラーを取り除く方法を知っていますか? – FRules