如何使用redis发布/订阅 [英] how to use the redis publish/subscribe

查看:43
本文介绍了如何使用redis发布/订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在使用 node.js 和 redis 来构建一个应用程序,我使用 redis 的原因是因为发布/订阅功能.该应用程序只是在用户进入用户或离开房间时通知管理员.

Currently I am using node.js and redis to build a app, the reason I use redis is because of the publish/subscribe feature. The app is simply to notify the manager when user comes into the user or out of room.

function publishMsg( channel , mssage){
    redisClient.publish(channel,JSON.stringify());
}

publishMsg('room/1/user/b',{'room':1,'user':'b'});
publishMsg('room/1/user/c',{'room':1,'user':'c'});
publishMsg('room/2/user/b',{'room':2,'user':'b'});
publishMsg('room/2/user/c',{'room':2,'user':'c'});

function subscribe(pattern){
    redisClient.psubscribe(pattern);
    redisClient.on('pmessage', function(pattern, channel, message){     
        console.log('on publish / subscribe   ',  pattern+"   "+channel+"    "+message+"   "+ JSON.parse( message) );
    });
}

既然我想听join和disjoin事件,我的问题是我应该使用两个 redisclient 来监听这两个事件,比如

since I want to listen to the join and disjoin event, my question is should I use two redisclient to listen these two events, like

   redisClient1.psubscribe('room/*/user/*/join');
   redisClient2.psubscribe('room/*/user/*/disjoin');

或者只用一个redisclient来监听和分离回调里面的逻辑

or just use one redisclient to listen and seperate the logic inside the callback

   redisClient2.psubscribe('room/*/user/*');

我知道这两种方式是可能的,但我不知道人们在现实中如何使用它们,在什么情况下?

I know these two ways are possible, But I don't know how in reality people use them, in which condition?

推荐答案

您可以安全地重复使用同一个 Redis 连接来订阅多个频道,但是您不能使用同一个连接来执行其他(与订阅无关的)任务.Redis 文档指出:

You can safely reuse the same Redis connection to subscribe to multiple channels, but you cannot use the same connection to perform other (non subscription-related) tasks. The Redis documentation states:

一旦客户端进入订阅状态,除了额外的 SUBSCRIBE、PSUBSCRIBE、UNSUBSCRIBE 和 PUNSUBSCRIBE 命令外,它不应发出任何其他命令.

Once the client enters the subscribed state it is not supposed to issue any other commands, except for additional SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE and PUNSUBSCRIBE commands.

我总是在 Node 中使用单个 Redis 连接来收听订阅的频道.

I always use a single Redis connection in Node to listen to subscribed channels.

这篇关于如何使用redis发布/订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆