首页 > 解决方案 > 与 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' }

标签: node.jsgoogle-app-engineredisgoogle-cloud-platformvpc

解决方案


我在不同的数据库中多次看到相同的问题。你已经发现了问题。打开的连接数 - 是有限且昂贵的资源。尝试使用以下模式(这只是一个示例):

   // 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);
   });



推荐阅读