我正在使用 node.js 和 redis,并通过此命令安装了hiredis 库
npm install hiredis redis
我在这里查看了多个示例:
https://github.com/mranney/node_redis/blob/master/examples/multi2.js https://github.com/mranney/node_redis/blob/master/examples/multi2.js
第 17 行说
// you can re-run the same transaction if you like
这意味着一旦命令执行完毕,内部 multi.queue 对象就永远不会被清除。
我的问题是:在http环境下你会如何处理这种情况?例如,跟踪最后一个连接的用户(这实际上并不需要 multi,因为它只执行一个命令,但很容易遵循)
var http = require('http');
redis = require('redis');
client = redis.createClient()
multi = client.multi();
http.createServer(function (request, response) {
multi.set('lastconnected', request.ip); // won't work, just an example
multi.exec(function(err, replies) {
console.log(replies);
});
});
在这种情况下,multi.exec 将为第一个连接的用户执行 1 个事务,为第 100 个用户执行 100 个事务(因为内部 multi.queue 对象永远不会被清除)。
选项1:我是否应该在 http.createServer 回调函数中创建多对象,这会在函数执行结束时有效地杀死它?创建和销毁该对象的 CPU 周期开销有多大?
选项2:另一种选择是创建一个新版本的 multi.exec(),例如 multi.execAndClear() ,它将在 redis 执行时清除队列that一堆命令。
您会选择哪个选项?我认为选项 1 更好 - 我们正在杀死一个对象,而不是挑选它的一部分 - 我只是想确定一下,因为我对节点和 JavaScript 都是全新的。