我有一个使用节点12的lambda函数。
我需要将新连接添加到托管在AWSElastiCache中的Redis数据库。
两者都在一个私有VPC并且安全组/子网配置正确。
解决方案:
global. 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;
助手/redis/index. js:
const get = require('./get');
module.exports = (redisClient) => {
return {
get: get(redisClient)
};
};
助手/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客户端错误:错误:Redis连接到…失败-连接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"
这不是配置问题,因为缓存在很短的时间内被访问了数百次,但随后它开始给出超时错误。
我认为这是问题的根源,可能redis数据库大小达到大小限制,无法处理新数据?
可以删除其中的旧数据吗?
此外,Elastic Cache可能对新TCP客户端的连接有限制,如果它耗尽,新连接将被拒绝,并出现您提到的类似错误消息。
如果aws lambda函数中的redis客户端无法建立连接,则aws lambda函数失败-并启动新函数。新的lambda函数会使一个连接redis,redis无法处理它,并启动另一个lambda函数…
因此,在某一时刻,我们达到了活动redis连接的极限,系统处于死锁状态。
我认为您可以暂时停止所有lambda函数,并扩展Elastic Cacheredis数据库。