NestJs:如何使TypeORMModule永久重试数据库连接?

时间:2020-09-23 21:07:21

标签: typescript nestjs typeorm

我有一个nestJS API。我正在使用TypeORM连接到数据库。我的API是一个docker容器。当我运行容器时,如果它无法连接到数据库,它将继续重试大约10次,然后退出。以下显示了部分日志:

> nest start

[Nest] 31   - 09/23/2020, 8:39:14 PM   [NestFactory] Starting Nest application...
[Nest] 31   - 09/23/2020, 8:39:14 PM   [InstanceLoader] TypeOrmModule dependencies initialized +39ms
[Nest] 31   - 09/23/2020, 8:39:14 PM   [InstanceLoader] AppModule dependencies initialized +1ms
[Nest] 31   - 09/23/2020, 8:39:14 PM   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +3ms
Error: getaddrinfo ENOTFOUND database database:5432
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
[Nest] 31   - 09/23/2020, 8:39:14 PM   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +3ms
Error: getaddrinfo ENOTFOUND database database:5432
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
[Nest] 31   - 09/23/2020, 8:39:17 PM   [TypeOrmModule] Unable to connect to the database. Retrying (2)... +3013ms
Error: getaddrinfo ENOTFOUND database database:5432
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
[Nest] 31   - 09/23/2020, 8:39:17 PM   [TypeOrmModule] Unable to connect to the database. Retrying (2)... +3ms
Error: getaddrinfo ENOTFOUND database database:5432
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
[Nest] 31   - 09/23/2020, 8:39:20 PM   [TypeOrmModule] Unable to connect to the database. Retrying (3)... +3010ms
Error: getaddrinfo ENOTFOUND database database:5432
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
[Nest] 31   - 09/23/2020, 8:39:20 PM   [TypeOrmModule] Unable to connect to the database. Retrying (3)... +2ms
Error: getaddrinfo ENOTFOUND database database:5432

我希望TypeORMModule能够永远重试。我想知道我该怎么做?

我的main.ts如下:

import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  await app.listen(3000);
}

bootstrap();

和以下app.module.ts:

import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { PostgresConnectionOptions } from "typeorm/driver/postgres/PostgresConnectionOptions";



@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useFactory: async () => {
        let options: PostgresConnectionOptions = {
          type: "postgres",
          host: "database",
          port: 5432,
          username: "test",
          password: "postgres",
          database: "test",
          migrationsRun: true,
        };
        return options;
      },
    }),
  ],
  controllers: [AppControlle],
  providers: [AppService],
})

export class AppModule {}

0 个答案:

没有答案