我已经使用redis 编写了一个简单的服务,用于将数据存储在内存中或从磁盘中获取数据然后存储在内存中。我现在正在尝试控制获取 redis 速度缓慢的罕见情况。我见过一个示例 ( https://gist.github.com/stockholmux/3a4b2d1480f27df8be67#file-timelimitedredis-js ),它似乎可以解决这个问题,但我在实现时遇到了麻烦。
链接的实现是:
/**
* returns a function that acts like the Redis command indicated by cmd except that it will time out after a given number of milliseconds
*
* @param {string} cmd The redis commmand to execute ('get','hset','sort', etc.)
* @param {integer} timeLimit The number of milliseconds to wait until returning an error to the callback.
*
*/
function timeLimited(cmd, timeLimit) {
return function() {
var
argsAsArr = Array.prototype.slice.call(arguments),
cb = argsAsArr.pop(),
timeoutHandler;
timeoutHandler = setTimeout(function(){
cb(new Error('Redis timed out'));
cb = function() {};
}, timeLimit);
argsAsArr.push(function(err, values){
clearTimeout(timeoutHandler);
cb(err,values);
});
client[cmd].apply(client,argsAsArr);
};
}
但是我不明白如何实现这一点,因为从未定义客户端并且从未传入 redis 键/值。有人可以解释一下如何实现这个例子吗?我一直在寻找更多信息或工作示例,但到目前为止没有任何运气。谢谢。
最佳答案
这写得不是很清楚,但是当你用cmd(例如SET、HSET等)和时间限制调用它时,它会返回一个函数。你用值调用这个返回的函数。我不知道客户来自哪里,我想你需要把它放在范围内。这不是很好的代码,我建议发布您编写的代码并询问如何实现您想要的代码。
关于node.js - 如何为redis请求设置 Node 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972689/