【问题标题】:Run NestJS scheduler without starting the HTTP server在不启动 HTTP 服务器的情况下运行 NestJS 调度程序
【发布时间】:2021-01-03 21:41:18
【问题描述】:

我正在尝试为 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 {}

data.scrapper.ts

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

【问题讨论】:

    标签: typescript nestjs scheduler


    【解决方案1】:

    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 生命周期事件

    【讨论】:

    • 我发现了两个问题:typescript const app = await NestFactory.createMicroservice(WorkerModule, { strategy: new KeepAliveStrategy(), // new() is required }); typescript wait() { if (!this.closing) { setTimeout(() =&gt; this.wait(), 1000); // should be () =&gt; this.wait() } }
    猜你喜欢
    • 2017-05-29
    • 2019-06-14
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    相关资源
    最近更新 更多