Mat*_*our 2 scheduler typescript nestjs
我正在尝试为 NestJS 创建一个“worker”,它基本上聚合来自多个数据源的数据。由于我将此工作程序部署到 Kubernetes 集群中,因此我不需要启动 NestJS 内部 HTTP 服务器,但是,调度程序不会在没有app.listen.
主要.ts:
async function bootstrap() {
const app = await NestFactory.create(WorkerModule);
await app.listen(3030); // <-- I would like to delete this
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
工作模块.ts
@Module({
imports: [
ScheduleModule.forRoot(),
],
providers: [
// Scrappers
DataScrapper,
],
})
export class WorkerModule {}
Run Code Online (Sandbox Code Playgroud)
数据抓取器.ts
@Injectable()
export class DataScrapper {
@Interval(1000)
async sync() {
console.log('fetching...');
}
}
Run Code Online (Sandbox Code Playgroud)
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: new KeepAliveStrategy(),
});
await workerApp.listen(() => console.log('listening'));
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
这将使您的工作线程保持活动状态并使其能够正确响应 NestJS 生命周期事件
| 归档时间: |
|
| 查看次数: |
1638 次 |
| 最近记录: |