【问题标题】:AWS Lambda: Redis ElastiCache connection timeout errorAWS Lambda:Redis ElastiCache 连接超时错误
【发布时间】:2022-01-02 07:50:42
【问题描述】:

我有一个使用 Node 12 的 lambda 函数。

我需要添加到托管在 AWS ElastiCache 中的 Redis 数据库的新连接。

两者都在一个私有 VPC 中,并且安全组/子网配置正确。

解决方案:

globals.js:

const redis = require('redis');
const redisClient = redis.createClient(
  `redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}/${process.env.REDIS_DB}`,
);
redisClient.on('error', (err) => {
  console.log('REDIS CLIENT ERROR:' + err);
});
module.exports.globals = {
  REDIS: require('../helpers/redis')(redisClient),
};

index.js(外部处理程序):

const { globals } = require('./config/globals');
global.app = globals;

const lambda_handler = (event, context, callback) => { ... }
exports.handler = lambda_handler;

helpers/redis/index.js:

const get = require('./get');
module.exports = (redisClient) => {
  return {
    get:  get(redisClient)
  };
};

helpers/redis/get.js:

module.exports = (redisClient) => {
  return (key, cb) => {
    redisClient.get(key, (err, reply) => {
      if (err) {
        cb(err);
      } else {
        cb(null, reply);
      }
    });
  };
};

函数调用:

app.REDIS.get(redisKey, (err, reply) => {
  console.log(`REDIS GET: ${err} ${reply}`);
});

问题: 当将 lambda 超时增加到大于 Redis 超时的值时,我收到此错误:

REDIS CLIENT ERROR:Error: Redis connection to ... failed - connect ETIMEDOUT ...

加法:

我尝试在每次交易后退出/关闭连接:

module.exports = (redisClient) => {

  return (cb) => {

    redisClient.quit((err, reply) => {
      if (err) {
        cb(err);
      } else {
        cb(null, reply);
      }
    });
  };
};
app.REDIS.get(redisKey, (err, reply) => {
  console.log(`REDIS GET: ${err} ${reply}`);
  if (err) {
    cb(err);
  } else {
    if (reply) {
      app.REDIS.quit(() => {
        cb()
      });
    }
  }
})

错误:

REDIS GET: AbortError: GET 无法处理。连接已关闭。

补充说明:

  • 我必须使用回调,这就是我在上面的示例中传递回调的原因
  • 我正在使用"redis": "^3.0.2"
  • 这不是配置问题,因为缓存在短时间内被访问了数百次,但随后开始出现超时错误。
  • 本地一切正常

【问题讨论】:

    标签: node.js amazon-web-services aws-lambda redis amazon-elasticache


    【解决方案1】:

    这不是配置问题,因为缓存在短时间内被访问了数百次,但随后开始出现超时错误。

    我认为是问题的根源,可能是redis数据库大小达到大小限制,无法处理新数据?

    可以删除里面的旧数据吗?

    Elastic Cache 也可能对新 TCP 客户端的连接有限制,如果它耗尽,新连接将被拒绝,并出现您提到的类似错误消息。

    如果 aws lambda 函数中的 redis 客户端无法建立连接,则 aws lambda 函数失败 - 并启动新的。新的lambda函数再连接redis,redis无法处理,又启动了一个lambda函数……

    所以,在某一时刻,我们达到了活动 redis 连接的限制,系统陷入了死锁。

    我认为您可以暂时停止所有 lambda 函数,并扩展 Elastic Cache redis 数据库。

    【讨论】:

    • 单个 ElastiCache for Redis 节点最多支持 65,000 个并发客户端连接。关于一些有用的配置/指标的任何想法,我可以检查其他可能的原因?
    猜你喜欢
    • 2020-11-01
    • 2017-05-23
    • 2020-10-26
    • 2021-06-12
    • 2018-07-16
    • 1970-01-01
    • 2016-07-10
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多