Redis / Node.js - 2 clients (1 pub/sub) causing issues with writes

情到浓时终转凉″ 提交于 2019-12-05 00:33:06

问题


Trying to create two clients; one is pub/sub, the other is a standard connection. Is this not possible? There must be a way to abstract this to work :) Basically, if I do a get key after running test.js, all I see is 'valueBefore'. The output:

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)

The code:

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
);

回答1:


You probably need to publish messages from client1 since client2 is dedicated to listening for messages on certain channel. Few words about this behavior are written in node_redis readme:

If you need to send regular commands to Redis while in pub/sub mode, just open another connection.



来源:https://stackoverflow.com/questions/7330496/redis-node-js-2-clients-1-pub-sub-causing-issues-with-writes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!