gpt4 book ai didi

node.js - 在 node.js 中监听 channel redis

转载 作者:可可西里 更新时间:2023-11-01 11:13:48 26 4
gpt4 key购买 nike

有这么简单的代码窃听萝卜 channel 。

redisClient = redis.createClient();
redisDummyPublishClient = redis.createClient();
//redisClient.auth("25c9721b4e579fc5af961f944e23f46f");


//look for connection errors and log
redisClient.on("error", function (err) {
console.log("error event - " + redisClient.host + ":" + redisClient.port + " - " + err);
});


var channels_active = [];
io.sockets.on('connection', function (socket) {
redisClient.on('ready', function() {
redisClient.psubscribe('*');
});


function CreateSocketsAccept (eventNameListen, channel, message){
var obj = { channel : channel, message : message}
for (i in eventNameListen) {
io.sockets.in(channel).emit(eventNameListen[i], obj);
}
}

redisClient.on('pmessage', function(pattern, channel, message) {
console.log(channel);
CreateSocketsAccept(channels_active, channel, message);
});

});

setInterval(function() {
var no = Math.floor(Math.random() * 100);
redisDummyPublishClient.publish('478669c7fa549970e36eac591cdca62e', 'Generated random no ' + no);
}, 5000);

从 PHP 发送数据:

$this->load->library( 'rediska_connector' );
// Other way to publish
$rediska = new Rediska();
$rediska->publish('realtime', 'PHP SENDING');

问题是,为什么不向控制台输出可用 channel 的名称?

最佳答案

据我所知,您无法收听所有 channel ...

如果你想订阅一个模式,你需要使用psubscribe:

redisClient.psubscribe('*');

而不是监听 message 事件,监听 pmessage 事件:

redisClient.on('pmessage', function(pattern, channel, message) {
console.log(channel);
});

(感谢@DidierSpezia 纠正我:)

编辑:您不能像那样混合使用 socket.io 和 Redis 客户端,您需要将 Redis 代码移到 socket.io处理程序:

// No need for this because it's doing nothing:
// io.sockets.on('connection', function(socket) { ... });

redisClient.on('ready', function() {
redisClient.psubscribe('*');
});

function CreateSocketsAccept (eventNameListen, channel, message){
var obj = { channel : channel, message : message}
for (i in eventNameListen) {
io.sockets.in(channel).emit(eventNameListen[i], obj);
}
}

redisClient.on('pmessage', function(pattern, channel, message) {
console.log(channel);
CreateSocketsAccept(channels_active, channel, message);
});

关于node.js - 在 node.js 中监听 channel redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20194820/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com