redis订阅问题:如果不用shell怎么发布订阅消息。

看到很多关于redis的例子,但是都是基于客户端命令行的,比如如下这种:

127.0.0.1:6379> publish channel message

那如果我现在不要用shell, 要用不同的浏览器订阅消息,然后在服务端发布消息,这个又怎么做呢? 我用的是node.js.
哪位大神可以放上浏览器客户端和服务端的订阅发布消息的例子,谢谢!

阅读 2.8k
2 个回答

我自己琢磨出了一种办法,不知道可行否。
我生成3个客户端:

  • 处理正常req,res请求的

  • 发布消息的

  • 订阅消息的

我本来想用订阅消息的redis客户端来处理正常req,res请求但是报错:

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

后来才知道,原来如果客户端用于订阅消息就不能下其他命令进行CRUD。
所以才要再建一个客户端处理正常的req, res请求。

下面是代码:

var redis = require('redis');
var express = require('express');
var app = express();
var clientSub = redis.createClient(6379, 'localhost');
var clientPub = redis.createClient(6379, 'localhost');
var clientRes = redis.createClient(6379,'localhost');

clientRes.on('ready', function(err){
    console.log('hello, i handle req/res');
});

clientPub.on('ready', function (err) {
    console.log('hello, i publish');
});

clientSub.on('ready', function (err) {
    console.log('hello, i subscribe');
});

clientSub.subscribe('channel1');

clientSub.on('subscribe', function (channel, count) {
    console.log(`got subscribe event: ${channel} and count is ${count}`);
    setInterval(()=>{
        clientPub.publish('channel1', `hi, i am channel one, message at ${new Date()}`);
    }, 2000);
});

clientSub.on('connect', function () {
    clientSub.on('message', function (channel, message) {
        var response = `received message from ${channel}:${message}`;
        clientRes.lpush('myResponse', response,redis.print);
    });
});

app.get('/', function (req, res) {
    clientRes.lrange('myResponse',0,-1, function(err, result){
        console.log(result[result.length])
        res.send(typeof result);
    })  
})

app.listen(1338, function () {
    console.log('App listening on port 1338!');
});

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题