小编典典

Redis / Node.js-2个客户端(1个发布/订阅)导致写入问题

redis

试图创建两个客户;一个是pub / sub,另一个是标准连接。这不可能吗?必须有一种将其抽象化的方法才能起作用:)基本上,如果我get key在运行test.js之后执行了一个操作,则看到的只是’valueBefore’。输出:

node test.js 
Reply: OK

/Users/franklovecchio/Desktop/development/node/node_modules/redis/index.js:487
        throw new Error("Connection in pub/sub mode, only pub/sub commands may
              ^
Error: Connection in pub/sub mode, only pub/sub commands may be used
    at RedisClient.send_command (/Users/franklovecchio/Desktop/development/node/node_modules/redis/index.js:487:15)
    at RedisClient.<anonymous> (/Users/franklovecchio/Desktop/development/node/node_modules/redis/index.js:597:27)
    at Object._onTimeout (/Users/franklovecchio/Desktop/development/node/distributed-cache/client/test.js:19:12)
    at Timer.callback (timers.js:83:39)

代码:

var redis = require('redis');

var client1 = redis.createClient();
var client2 = redis.createClient();

client2.on('message', function (channel, message) {
    console.log('Received a message on channel: ' + channel);

    client1.set('key', message, redis.print);

});

client2.subscribe('channel');

client1.set('key', 'valueBefore', redis.print);

setTimeout(
    function() {
        client2.publish('channel', 'valueAfter');
    },3000
);

阅读 261

收藏
2020-06-20

共1个答案

小编典典

您可能需要发布来自的消息,client1因为client2它专门用于侦听某些频道上的消息。在node_redis自述文件中几乎没有关于此行为的文字:

如果在发布/订阅模式下需要向Redis发送常规命令,只需打开另一个连接即可。

2020-06-20