【问题标题】:Logging slow redis operations in NodeJS在 NodeJS 中记录缓慢的 redis 操作
【发布时间】:2021-10-07 22:29:17
【问题描述】:

在 Nodejs 应用程序中,我使用 'ioredis' npm 模块来执行所有 redis 操作。 Redis 在整个服务中被大量使用。但是我已经看到 1 of 1000 调用,redis 延迟增加到 400 毫秒。

我正在尝试在代码本身中记录所有超过某个时间戳的 redis 操作。建议一些方法来记录此类命令,而不会减慢任何其他操作。 谢谢。

【问题讨论】:

    标签: node.js redis ioredis


    【解决方案1】:

    你可以试试这个:

    var Moment = require('moment');
    
    var start_time = Moment();
    
    
    //->>> In case of Promises
    
    redisOperation(arguments)
    .then(function() {
       var time_taken = Moment() - start_time;
       console.log(time_taken); //However you want to log, use the logger function here
    });
    
    
    
    //->>> In case of Callback Function
    
    redisOperation(arguments, function() {
        var time_taken = Moment() - start_time;
        console.log(time_taken); //However you want to log, use the logger function here
    
        cb();
    });
    

    【讨论】:

    • 嗨 Prerna,感谢您的回复。我探索了这个选项,但这会导致额外的开销。 ioredis 模块或类似于 tthat 的东西是否还有其他更好的内置操作。
    • 好的,尚不知道 Pavneet 有关于 ioredis 的任何内置操作,这些操作可以为您调用该特定函数提供响应时间。如果我遇到任何问题,会在这里提及。
    • 你也可以试试这个方法:************ console.time("redis_function") and console.timeEnd("redis_function") **** ******** 例如,这实际上会减少导入 Moment 等任何模块的开销。
    【解决方案2】:

    暂时,我无法找到任何内置解决方案。但是我通过在执行 Redis 操作之前创建一个包装器来处理这个问题。

    const traceTime = function (fn) {
       return async function (...args) {
          const startTime = Date.now();
          const executionResp = await fn.apply(this, args);
          const endTime = Date.now();
       };
    }
    
    /* wrap the redis operations with traceTime */
    
    set = traceTime(set); // redis set operation
    get = traceTime(get); // redis get operation
    
    
    /* use redis set operation, wherever you want to use,           
      it will log startTime and endTime and execute redis operation from there */
    set(key, value, (err, response) => { 
       // err and response handler 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2020-06-29
      • 1970-01-01
      • 2017-08-21
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多