Redis發佈訂閱
- Redis發佈訂閱是一種消息通信模式:發送者發送消息,訂閱者接收消息,客戶端可以訂閱任意數量的頻道。
命令行中使用Redis的發佈訂閱
SUBSCRIBE channel_a //訂閱頻道a
PUBLISH channel_a hello //向頻道a發佈內容hello
- 這時候會在客戶端1收到客戶端2發佈的hello字符串
在node中如何使用Redis訂閱發佈
let redis = require("redis");
let client1 = redis.createClient(6379,"127.0.0.1");
let client2 = redis.createClient(6379,"127.0.0.1");
let count = 0;
//訂閱頻道
client1.subscribe("channel_a");
client1.subscribe("channel_b");
//監聽消息
client1.on("message",(channel,message) => {
//當收到第一條消息之後,立刻取消訂閱頻道channel_b,那以後將不再接受頻道B發過來的消息
console.log(channel,message);
//取消訂閱
client1.unsubscribe("channel_b");
})
client2.publish("channel_a","hello");
client2.publish("channel_b","world");
setTimeout(() => {
client2.publish("channel_a","hello2");
client2.publish("channel_b","world2");//這個不會被接受了,因爲第一次消息收到後就取消訂閱channel_b了
},2000)
setInterval(() => {
client2.publish("channel_a",++count);
},1000)