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

1.新建文件 redis_db.js

javascript 复制代码
'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

javascript 复制代码
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 测试同个进程的

javascript 复制代码
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 测试同个进程的

javascript 复制代码
// 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()
javascript 复制代码
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.大功告成

相关推荐
1314lay_10072 分钟前
Vue+C#根据配置文件实现动态构建查询条件和动态表格
javascript·vue.js·elementui·c#
SuperEugene6 分钟前
Vue3 前端配置驱动避坑:配置冗余、渲染性能、扩展性问题解决|配置驱动开发实战篇
前端·javascript·vue.js·驱动开发·前端框架
JianZhen✓9 分钟前
从零到一:基于声网Agora的医疗视频问诊前端实战指南
前端·音视频
GISer_Jing12 分钟前
LangChain浏览器Agent开发全攻略
前端·ai·langchain
小李子呢021120 分钟前
前端八股---脚手架工具Vue CLI(Webpack) vs Vite
前端·vue.js·webpack
gCode Teacher 格码致知20 分钟前
Javascript提高:Math.round 详解-由Deepseek产生
开发语言·javascript
2401_8858850422 分钟前
群发彩信接口怎么开发?企业级彩信发送说明
前端·python
织_网23 分钟前
Nest.js:Node.js后端开发的现代企业级解决方案,赋能AI全栈开发
javascript·人工智能·node.js
PILIPALAPENG24 分钟前
第2周 Day 5:前端转型AI开发,朋友问我,你到底在折腾啥?
前端·人工智能·python
Mintopia29 分钟前
前端卡顿的真相:不是你代码慢,是你阻塞了
前端