懒得描述了直接上demo
const redis = require('redis');
const client = redis.createClient("6379", "localhost", { detect_buffers: true })
client.auth('123456')
const redis2 = require('redis');
const client2 = redis2.createClient("6379", "localhost", { detect_buffers: true })
client2.auth('123456')
function getRedisData() {
client2.on('ready', function () {
client2.subscribe("chat");
console.log("订阅成功");
})
client2.on('error', function (error) {
console.log("ERROR:" + error);
})
//监听订阅成功事件
client2.on("subscribe", function (channel, count) {
console.log("客户从连接" + channel + "队列,一个连接" + count + " 已经订阅成功!");
});
client2.on("message", function (channel, message) {
// console.log(channel)
console.log("我收到消息了: " + message)
//使用set操作,根据给定的message检测redis中是否存在该数据,如果存在则删除该数据。
client.srem("push:" + channel, message, function (err, res) {
console.log(res)
})
})
client2.on("unsubscribe", function (channel, count) {
console.log("客户端从连接断开 " + channel + "," + count + " 一个连接断开");
})
}
getRedisData();
function producer(key, value) {
//set操作
client.sadd(key, value, function (err, res) {
// console.log(res)
if (res == 1) {
client.publish("chat", value);
}
})
}
for (var i = 0; i < 5; i++) {
producer("push:chat", "第" + i + "条消息");
}