typescript - 在不启动 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...');
}
}
解决方案
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 生命周期事件
推荐阅读
- javascript - 使用javascript使用嵌套对象数组进行对象动态过滤
- android - React 本机发布模式没有获得最后的代码更新
- c# - 使用 AJAX 调用使用新模型重新加载视图
- python - 如何在 Groupby 中保留其他列的行值?
- yaml - 使用 GitLab CI 如何禁用一项作业的存储库克隆?
- arduino - Arduino COM 端口灰显
- database - 我可以更改 PostgreSQL 中为重复键引发的错误消息吗?
- java - 在模块 auto-value-1.2.jar 中发现重复的类 com.google.auto.value.AutoAnnotation
- html - 使用带有 ngb-accordion 的点击功能
- sql - 表排序规则什么时候会改变?