首页 > 解决方案 > 在不启动 HTTP 服务器的情况下运行 NestJS 调度程序

问题描述

我正在尝试为 NestJS 创建一个“worker”,它基本上聚合了来自多个数据源的数据。由于我将此工作程序部署到 Kubernetes 集群中,因此我不需要启动 NestJS 内部 HTTP 服务器,但是,调度程序不会在没有app.listen.

main.ts:

async function bootstrap() {
  const app = await NestFactory.create(WorkerModule);
  await app.listen(3030); // <-- I would like to delete this
}

bootstrap();

worker.module.ts

@Module({
  imports: [
    ScheduleModule.forRoot(),
  ],
  providers: [
    // Scrappers
    DataScrapper,
  ],
})
export class WorkerModule {}

数据.scrapper.ts

@Injectable()
export class DataScrapper {
  @Interval(1000)
  async sync() {
    console.log('fetching...');
  }
}

标签: typescriptnestjsscheduler

解决方案


NestJS 的核心是一个模块化框架,为节点/TS 生态系统提供强大的 DI 能力。可以通过以下三种方式之一公开顶级模块:

您可以通过使用自定义策略将应用程序创建为微服务来完成您想要的。我很可能会将这种模式打包为@golevelup/nestjs生态系统的一部分(免责声明,我是作者),因为我最近遇到这种模式的频率越来越高。

import { CustomTransportStrategy } from '@nestjs/microservices';

class KeepAliveStrategy implements CustomTransportStrategy {
  private closing = false;

  wait() {
    if (!this.closing) {
      setTimeout(this.wait, 1000);
    }
  }

  listen(callback: () => void) {
    callback();
    this.wait();
  }

  close() {
    this.closing = true;
  }
}

async function bootstrap() {
  const workerApp = await NestFactory.createMicroservice(WorkerModule, {
    strategy: KeepAliveStrategy,
  });

  await workerApp.listen(() => console.log('listening'));
}
bootstrap();

这将使您的工作人员保持活力并允许它正确响应 NestJS 生命周期事件


推荐阅读