Nodejs 为 Redis 请求设置超时 [英] Nodejs set timeout for Redis requests

查看:56
本文介绍了Nodejs 为 Redis 请求设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的服务,使用 redis 将数据存储在内存中或从磁盘中提取然后存储在内存中,并希望为慢速请求设置超时.我希望找到一种方法来发出一个超时的 get 请求,以防止这个请求挂起.任何帮助表示赞赏.

I've written a simple service using redis to store data in memory or fetch from disc and then store in memory and want to set a timeout for slow requests. I'm hoping to find a way make a get request with a timeout to prevent this a request from hanging. Any help is appreciated.

推荐答案

因此,您可以在这里做一些事情.但是,首先我想知道您是否正在尝试过早优化.在大多数正常情况下,Redis 的速度非常快,如果您在客户端上发现性能问题,则表明您的数据或在 Redis 中处理数据的方式存在问题.这应该在 redis 中修复,您不应该在客户端中执行任何操作来处理慢速请求.

So, there are a few things you can do here. But, first I wonder if you are attempting premature optimization. Redis in most normal situations is blazingly fast, and if you are finding performance issues on the client, then that indicates that you have some issues with your data or how you are processing it in redis. This should be fixed this in redis, there is nothing you should do in your client to handle slow requests.

那么,如果您看到偶尔的减速,它们是什么原因造成的?这不是一个正常的 redis 问题,应该解决而不是寻找 javascript 修复程序.

So, if you are seeing occasional slowdowns, what are they coming from? This is not a normal redis issue, and should be addressed instead of looking for a javascript fix.

如果您仍在寻找 javascript 修复程序,您可以执行以下操作:

If you are still looking for a javascript fix, you could do something like this:

const client = require('redis').createClient(...);

export async function asyncSetEx(key) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      reject(new Error('Timed out'));
    });
    client.setEx(key, (res, err) => {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
      clearTimeout(timer);
    });
  });
}

不过,我建议对此进行概括,以便它适用于具有任意数量参数的任何 redis 函数.

Though, I'd recommend generalizing this so that it works for any redis function with any number of parameters.

这篇关于Nodejs 为 Redis 请求设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆