node.js - 如何为redis请求设置 Node 超时

标签 node.js redis

我已经使用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/

相关文章:

node.js - 如何递归比较 Node 中的两个目录

node.js - Sequelize 部署同步

redis - 为什么redis只用little endian存储内存数据?

android - 用于分析用户移动应用程序 Activity 的数据库 - Mongo 或 Redis 或其他?

hash - 如何从 redis geohash 中删除一个项目?

model - Redis 建模和查询

node.js - Nodejs mongo返回带有分页信息的数据

jquery - 如何创建要订阅的 View 的路径,由 bayeux.getClient().publish(

node.js - 如何自动化API获取数据请求?使用网络套接字时

redis - 一段时间后带有redis的spring-data-redis出现异常: could not get a resource from the pool