Redis / Node.js - 2 个客户端(1 个发布/订阅)导致写入问题
尝试创建两个客户端;一种是发布/订阅,另一种是标准连接。这不可能吗?必须有一种方法来抽象它才能工作:) 基本上,如果我在运行 test.js 后执行 get key
,我看到的只是“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
);
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
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要从
client1
发布消息,因为client2
专用于侦听特定通道上的消息。 node_redis 自述文件中只写了关于此行为的几句话:You probably need to publish messages from
client1
sinceclient2
is dedicated to listening for messages on certain channel. Few words about this behavior are written in node_redis readme: