ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[toc] Redis 发布订阅是一种消息通信模式:发送者发送消息,订阅者接收消息,客户端可以订阅任意数量的频道。 ![](http://img.zhufengpeixun.cn/redissubscribe.jpg) ## 命令行操作 ![](https://box.kancloud.cn/5dae568fa44921a71171699f6ff499ab_661x634.png) ## 用node操作 ``` const redis = require('redis'); let client1 = redis.createClient(6369,'localhost'); let client2 = redis.createClient(6369,'localhost'); //client1订阅了food drink两个频道 client1.subscribe('food'); client1.subscribe('drink'); //指定当收到订阅的消息之后要干什么 client1.on('message',function(channel,message){ console.log(channel,message); client.unsubscribe('food'); //以后再也不接受食品频道的消息 }); //client2向频道food 和 drink发送 消息 //监听比较慢 需要延时发送 setTimeout(function(){ client2.publish('food','面包'); client2.publish('drink','可乐'); setTimeout(function(){ client2.publish('food','面包2'); client2.publish('drink','可乐2'); },1000); },1000); ```