node.js - 与 Redis 实例的连接每隔几分钟关闭一次
问题描述
我在使用 redis 缓存服务器的 Google Cloud 上运行 node.js。它运行了几个月,但它突然开始抛出连接错误并且偶尔停止响应。
该应用程序在标准环境中运行,并通过 VPC 连接器连接到运行 Redis 实例的 VM。我怀疑这是一个网络问题,因为当我从自己的计算机(连接到同一个 Redis 服务器)运行 Node.js 应用程序时,或者当应用程序在 flex 环境中运行并连接到直接子网。但是,我更喜欢该应用程序在标准环境中运行,因为据我所知,这是通过 https 强制流量的唯一方法。
当我通过 Redis-cli 进行监控时,服务器在连接失败时不会收到任何命令。
redis.conf 中的超时设置为 0
Redis 版本:5.0.5
这是 Redis 代码。我不认为这是问题,几周前它运行没有问题。
const redis = require('redis')
const redisOptions = {
host: process.env.REDIS_IP,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PASS,
enable_offline_queue: false,
}
const client = redis.createClient(redisOptions.host, redisOptions.port)
// Log any errors
client.on('error', function(error) {
console.log('Error:')
console.log(error)
})
module.exports = client
这些错误会定期显示在 Google App 引擎日志中。当它们发生时,发送到 Redis 的命令不会显示在日志中。
A 2019-08-31T12:42:27.162834Z { Error: Redis connection to 10.128.15.197:6379 failed - read ETIMEDOUT "
A 2019-08-31T12:42:27.162868Z at TCP.onStreamRead (internal/stream_base_commons.js:111:27) errno: 'ETIMEDOUT', code: 'ETIMEDOUT', syscall: 'read' }
解决方案
我在不同的数据库中多次看到相同的问题。你已经发现了问题。打开的连接数 - 是有限且昂贵的资源。尝试使用以下模式(这只是一个示例):
// Inside your db module
function dbCall(userFunc) {
const client = anyDb.createClient(host, port, ...);
userFunc(client, () => { client.quit(); /* client.close() or whatever */ }
}
// Usage
dbCall((client, done) => {
client.doSomethingWithCallback(..., () => {
// user code
done();
});
});
dbCall((client, done) => {
client.doSomePromise(...)
.finally(done);
});
推荐阅读
- reactjs - Material-UI DataGrid 隐藏特定单元格的标题分隔符
- iis - IIS - 尽管 web.config 不存在,但 X-Frame-Options 设置为 SAMEORIGIN
- reactjs - react-bootstrap 表单按钮在第一次点击时不提交
- postgresql - ECS 中的 PostgreSQL:'致命:角色“root”不存在'
- powershell - Powershell用括号将变量传递给其他变量
- c# - 使用字符串中的密钥通过 SSH.NET 对 SFTP 进行身份验证时出现“无效的私钥文件”
- trello - 查找谁在 Trello Boad 中创建了卡片
- regex - 通过 JMX 为 Druid 进行 mBean 模式匹配
- jenkins - 发布关于 Jenkins 的 HTML 报告不起作用
- python - 弄清楚如何使用 python 压缩文件/文件夹