はじめに
Redisのドキュメントで、Clusterに対応したライブラリとして紹介されているthunk-redisで、PubSubが出来るか試してみた。
環境
以下の環境で試した。
thunk-redis
0.9.6
redis-server
$ redis-server -v
Redis server v=3.1.999 sha=0610cb62:0 malloc=jemalloc-3.6.0 bits=64 build=673c3bffc00a919c
Redis Cluster
127.0.0.1:7000> cluster nodes
d64dd6fd3e5cea7d0cf87acb278d94c7d1e02bca 127.0.0.1:7001 master - 0 1431065679491 2 connected 5461-10922
5b889edfad0301cebb997bb92fe84f6e097e0ff8 127.0.0.1:7005 slave 22bca92b78354dc995b35c815c54936f6efc28d4 0 1431065678987 6 connected
f254c575fd2f06161905753f9e473c569ce4cdcf 127.0.0.1:7003 slave 93e53337037a3f9b1a5e0ae914e48aeca54a1d7b 0 1431065679997 4 connected
590b0db9b2031254645be39104aafb865bc70d31 127.0.0.1:7004 slave d64dd6fd3e5cea7d0cf87acb278d94c7d1e02bca 0 1431065681012 5 connected
93e53337037a3f9b1a5e0ae914e48aeca54a1d7b 127.0.0.1:7000 myself,master - 0 0 1 connected 0-5460
22bca92b78354dc995b35c815c54936f6efc28d4 127.0.0.1:7002 master - 0 1431065680503 3 connected 10923-16383
プログラムの説明
実際にプログラムを書いて挙動を確認したので、簡単に説明する。
プログラムは、thunk-redis-pubsubにある。
プログラムは、Publishモード・Subscribeモードで動作するCLIである。
Publishモードで起動する
pub
コマンドを指定し、--channel
オプションにチャネルを、--message
オプションにPublishするメッセージを指定して起動する。
実行が完了したら、プログラムは直ちに終了する。
$ node index.js pub --port 7000 --channel my-channel --message Hello
* connect
1
Subscribeモードで起動する
sub
コマンドを指定し、--channel
オプションにチャネルを指定して起動する。
sub
コマンドは、publishされるメッセージを待ち受ける。
$ node index.js sub --port 7000 --channel my-channel
subscribed: channel=my-channel
* message: (my-channel, Hello)
気づいたこと
クラスタモードの指定は不要?
createClient()
のオプションで、{clusterMode: (true|false)}を指定できるが、どうも自動的に判別しているようだ。
thunk-redisで、clusterMode
をtrue
/false
を指定して、Redisの状態をダンプしてみた。
var testClusterMode = function(clusterMode) {
var client = redis.createClient(7000, {clusterMode: clusterMode});
client.on('connect', function() {
console.log('*** clusterMode=%s', clusterMode);
console.dir(client.clientState());
client.clientEnd();
});
};
[true, false].forEach(function(clusterMode) {
testClusterMode(clusterMode);
});
結果は以下。
clusterModeにtrue
を設定してもfalse
を設定しても、clientState()
で得られたclusterModeは、true
である。
$ npm run start
> hello-thunk-redis@0.0.1 start /home/hina/devel/hello-thunk-redis
> node index.js
*** clusterMode=true
{ pool:
{ '127.0.0.1:7000': [ '127.0.0.1:7003' ],
'127.0.0.1:7001': [ '127.0.0.1:7004' ],
'127.0.0.1:7002': [ '127.0.0.1:7005' ] },
ended: false,
clientId: 1,
database: 0,
connected: true,
timestamp: 1431066031652,
clusterMode: true,
defaultConnection: '127.0.0.1:7000',
commandQueueLength: 0 }
*** clusterMode=false
{ pool:
{ '127.0.0.1:7000': [ '127.0.0.1:7003' ],
'127.0.0.1:7001': [ '127.0.0.1:7004' ],
'127.0.0.1:7002': [ '127.0.0.1:7005' ] },
ended: false,
clientId: 2,
database: 0,
connected: true,
timestamp: 1431066031654,
clusterMode: true,
defaultConnection: '127.0.0.1:7000',
commandQueueLength: 0 }
結論
Publish/Subscribeは、Cluster構成でも正常に動作するようだ。