【发布时间】: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