如何使用TypeORM检查是否仍与数据库建立连接?

问题描述 投票:0回答:1

我在使用 AWS lambdas + RDS Proxy的无服务器架构中使用 typeorm "typeorm": "0.3.9"。

根据我在互联网上找到的一些建议,我选择在执行 lambda 后保持连接打开,以便下一次 lambda 执行时可以重用它。

我的问题是,在一种情况下,我的 RDS 代理关闭了一个连接(它认为该连接处于空闲状态),但 lambda 仍在使用该连接的引用,然后发生错误。

为了解决这个问题,我尝试使用 typeorm 检查是否存在以下代码的活动连接:

// Returns true even when the RDS Proxy has already killed the connection.
if (!this.dataSource.isInitialized) {
  await this.dataSource.initialize();
}

当我测试它时,我注意到该验证知道存在已建立的连接,即使 RDS 代理已经终止了连接。

有人可以建议我一种方法,在打开新连接之前检查是否已建立与数据库的连接吗?

typescript aws-lambda amazon-rds typeorm amazon-rds-proxy
1个回答
0
投票

我找到了一个很好的解决方案。只需运行查询并在失败时重新建立连接即可。

这是来自中间件的片段,但你应该能够明白我的意思......

      if (datasource) {
        try {
          // run a quick query to validate the connection, the lambda may have destroyed it
          await datasource.query('select version()');
          request.context.datasource = datasource;
          // We have a valid connection we can return;
          return;
        } catch (e) {
          console.warn('check connection failed, re-establishing connection', e);
          datasource = undefined;
        }
      }
      ... establish a connection
© www.soinside.com 2019 - 2024. All rights reserved.