Redis入門シリーズのキューと購読モードのリリース


一.Redis実現キュー
前に述べましたが、lpushを使ってrpopまたはrpushを合わせてlpopを組み合わせると、列が実現できます。Redisは待ち時間をブロックする方法を提供しています。列の中が空いているなら、待ち時間をブロックします。
生産者:
localhost:6379> lpush queue 5 4 3 2 1
(integer) 5

消費者:
localhost:6379> BRPOP  queue 0
1) "queue"
2) "5"
(67.95s)
localhost:6379> BRPOP  queue 0
1) "queue"
2) "4"
localhost:6379> BRPOP  queue 0
1) "queue"
2) "3"
localhost:6379> BRPOP  queue 0
1) "queue"
2) "2"
localhost:6379> BRPOP  queue 0
1) "queue"
2) "1"
localhost:6379> BRPOP  queue 0
brpop key time
タイムはブロック待ちの時間で、0は無限待ちを表します。
列のqueueの中は空いていますので、待ち時間が詰まります。
Redisはキューを取る際に優先度をサポートします。
生産者:
localhost:6379> lpush queue:1 5 4
(integer) 2
localhost:6379> lpush queue:2 2 1 0
(integer) 3
消費者:
localhost:6379> brpop queue:1 queue:2 10 
1) "queue:1"
2) "5"
localhost:6379> brpop queue:1 queue:2 10 
1) "queue:1"
2) "4"
localhost:6379> brpop queue:1 queue:2 10 
1) "queue:2"
2) "2"
localhost:6379> brpop queue:1 queue:2 10 
1) "queue:2"
2) "1"
localhost:6379> brpop queue:1 queue:2 10 
1) "queue:2"
2) "0"
localhost:6379> brpop queue:1 queue:2 10 
(nil)
(10.32s)
  bpopの後ろに複数の列を置くとき 前の列は優先度が高いです。前の列を取り出して後ろの列を取ります。
二.発行/購読
すべての購読者は投稿者の内容を受け取ることができます。また、redisのリストを利用して実現されます。しかし、発表者が発表した内容は保存されません。だから、チャンネルに購読者がいないと、メッセージは直接失われます。
投稿者:
localhost:6379> publish channel hi
(integer) 0
    この時、チャンネルはまだ予約者がいませんので、戻りの結果は0です。
購読者:
localhost:6379> subscribe  channel 
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel"
3) (integer) 1
このように毎回発表者がメッセージを発表した後、このチャンネルに購読しているすべての購読者はメッセージを受け取ることができます。