示例javascript
// 引入redis let redis = require("redis"); // 建立鏈接 let client = redis.createClient(6379, "127.0.0.1"); client.on("ready", function () { //訂閱消息 client.subscribe("chatB"); }); // 失敗處理 client.on("error", function (error) { console.log("Redis Error " + error); }); //監聽訂閱成功事件 client.on("subscribe", function (channel, data) { console.log("client subscribed to " + channel + ",data:" + data); }); //收到消息後執行回調,message是redis發佈的消息 client.on("message", function (channel, message) { console.log("我接收到信息了" + message); }); //監聽取消訂閱事件 client.on("unsubscribe", function (channel, count) { console.log("client unsubscribed from" + channel + ", " + count + " total subscriptions") }); function zadd(channel, data) { client.publish("chatA", data);//client將member發佈到chat這個頻道 //而後訂閱這個頻道的訂閱者就會收到消息 } for (let i = 0; i < 10; i++) { zadd("z", "" + i);//發佈10次 }
let redis = require("redis"); let client = redis.createClient(6379, "127.0.0.1"); //客戶端鏈接redis成功後執行回調 client.on("ready", function () { //訂閱消息 client.subscribe("chatA"); }); // 失敗處理 client.on("error", function (error) { console.log("Redis Error " + error); }); //監聽訂閱成功事件 client.on("subscribe", function (channel, data) { console.log("client subscribed to " + channel + ",data:" + data); }); //收到消息後執行回調,message是redis發佈的消息 client.on("message", function (channel, message) { console.log("我接收到信息了" + message); }); //監聽取消訂閱事件 client.on("unsubscribe", function (channel, count) { console.log("client unsubscribed from" + channel + ", " + count + " total subscriptions") });
先執行readRedis.js,後執行publish.js,readRedis.js的控制檯輸出:java
我接收到信息了0 我接收到信息了1 我接收到信息了2 我接收到信息了3 我接收到信息了4 我接收到信息了5 我接收到信息了6 我接收到信息了7 我接收到信息了8 我接收到信息了9
每一個文件均可以監聽和發佈消息。redis