2个nodejs进程利用redis 实现订阅发布

1.新建文件 redis_db.js

'use strict';

const redis = require('redis');
const options = {
    host: "127.0.0.1",
    port: 6379,
    password: "123456", // CONFIG SET requirepass "123456"
}

var array = []
for(var i=0; i<3; i++){
    const client = redis.createClient(options)
    array.push(client)
}

function getDB(index){
    if(typeof index === "number"){
        return array[index]
    }
    return array
}

for(var key in array){
    const client = array[key]
    client.on('error', err => console.log('------ client Redis connection failed ------' + err))
        .on('connect', () => console.log('------ client Redis connection succeed ------')
    )
}

module.exports = {
    getDB,
}

备注1:安装 reids 啥的就不说了

【保姆级】Redis安装教程(Windows版)_windows安装redis-CSDN博客

linux环境安装redis(亲测完成)_linux 斌阿姨安装redis-CSDN博客

备注2:新增3个redis的连接:  [0] 是之前的;  [1] 用于sub; [2] 用于pub

如果没有多个的话,sub和pub的时候会报错 

ReplyError: ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context

2.新建文件 redis_ipc.js

var redis_db = require("./redis_db.js");
const clients  = redis_db.getDB()
const client1  = clients[1]
const client2  = clients[2]

function mySub(channelName, handleMessage){
    // 订阅指定的频道
    client1.subscribe(channelName, (err, channels) => {
        if (err) {
            console.error('无法订阅频道:', err);
        } else {
            // 设置每次收到新消息时调用的处理函数
            client1.on('message', handleMessage);
        }
    })
}

function myPub(channelName, messageContent){
    client2.publish(channelName, messageContent, (err, reply) => {
        if (!err && reply === 0) {
            console.log(`消息 "${messageContent}" 未被任何人接收。`);
        } else if (!err && reply > 0) {
            console.log(`消息 "${messageContent}" 已成功发送给 ${reply} 个订阅者。`);
        } else {
            console.error('发送消息失败:', err);
        }
    });
}

module.exports = {
    mySub,
    myPub,
}

3.新增测试代码

3.1新建文件test01.js 测试同个进程的


const redis_ipc = require('./redis_ipc.js')
function testSubPub(){
    const channelName = 'test_channel_1';
    function handleMessage(channel, message) {
        // 在这里编写处理收到消息后的操作
        console.log(`收到来自 ${channel} 通道的消息:${message}`);
    }
    redis_ipc.mySub(channelName, handleMessage)

    const messageContent = '{"data":{"name":"xxx","age":"18"}}';
    redis_ipc.myPub(channelName, messageContent)
}

testSubPub()

目录如下:

执行指令:node .\test01.js

3.2新建文件test02.js test03.js 测试同个进程的

// test02.js
const redis_ipc = require('./redis_ipc.js')
function testSubPub(){
    const channelName = 'test_channel_1';
    function handleMessage(channel, message) {
        // 在这里编写处理收到消息后的操作
        console.log(`收到来自 ${channel} 通道的消息:${message}`);
    }
    redis_ipc.mySub(channelName, handleMessage)

    // const messageContent = '{"data":{"name":"xxx","age":"18"}}';
    // redis_ipc.myPub(channelName, messageContent)
}

testSubPub()
test03.js
const redis_ipc = require('./redis_ipc.js')
function testSubPub(){
    const channelName = 'test_channel_1';
    // function handleMessage(channel, message) {
    //     // 在这里编写处理收到消息后的操作
    //     console.log(`收到来自 ${channel} 通道的消息:${message}`);
    // }
    // redis_ipc.mySub(channelName, handleMessage)

    const messageContent = '{"data":{"name":"xxx","age":"18"}}';
    redis_ipc.myPub(channelName, messageContent)
}

testSubPub()

订阅者:先在一个终端执行 node .\test02.js 

发布者:再在一个终端执行 node .\test03.js

观察第一个终端 会收到 发布者的消息

4.大功告成

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Node.js中使用Redis订阅功能,可以通过引入`redis`模块并创建Redis客户端来实现。首先,需要在Redis配置文件中启用键空间通知功能,可以通过在Redis程序根目录下的命令行窗口执行以下命令来实现:`./redis-cli config set notify-keyspace-events Ex` [1。 然后,在Node.js代码中,使用`redis`模块创建两个Redis客户端实例,并通过`subscribe`方法订阅消息频道,例如`chat`和`chat1`。当订阅成功后,可以在`subscribe`事件回调函数中处理相关逻辑。同时,可以在`message`事件回调函数中接收到订阅频道发布的消息,并进行相应的业务处理。最后,在`unsubscribe`事件回调函数中可以取消订阅。以下是一个示例代码: ```javascript var redis = require("redis"); var client = redis.createClient(6379, "127.0.0.1"); var client1 = redis.createClient(6379, "127.0.0.1"); function getRedisData() { client.on("ready", function () { client.subscribe("chat"); client.subscribe("chat1"); console.log("订阅成功。。。"); }); client.on("error", function (error) { console.log("Redis Error " + error); }); client.on("subscribe", function (channel, count) { console.log("client subscribed to " + channel + ", " + count + " total subscriptions"); }); client.on("message", function (channel, message) { console.log("我接收到信息了:" + message); // 在这里处理业务逻辑 }); client.on("unsubscribe", function (channel, count) { console.log("client unsubscribed from " + channel + ", " + count + " total subscriptions"); }); } getRedisData(); ``` 需要注意的是,Redis的键空间通知功能是基于发布订阅模型的,而订阅频道是固定的`__keyevent@0__:expired` [2。通过设置键的过期时间并使用发布订阅模式,可以接收到键过期的通知,并执行相应的业务逻辑。例如,在Redis中可以使用`expire`命令设置键`test`的过期时间,然后通过订阅`__keyevent@0__:expired`频道来接收键过期的通知 [3。 希望以上信息能帮助到您。如果还有其他问题,请随时提问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [NodeJS 使用redis实现定时执行方法](https://blog.csdn.net/huyande123/article/details/112854509)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值