Redis订阅发布

懒得描述了直接上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 + "条消息");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值