繁体   English   中英

Nest.js async onModuleInit 无效排序

[英]Nest.js async onModuleInit invalid ordering

我有ServiceA依赖于RedisService

要初始化ServiceA ,需要RedisService已经初始化(即RedisService.onModuleInit已被调用并等待)

这是 ServiceA 定义:


// module config
@Module({
    imports: [RedisModule],
    controllers: [ServiceAController],
    providers: [ServiceAService, RedisService],
})
export class ServiceAModule {}

class ServiceA {
    constructor(
        private readonly redisService: RedisService,
    ) {}

    async onModuleInit(): Promise<void> {
        this.logger.debug('Initializing ServiceA...')
        const client = await this.redisService.getClient()
        // do some stuff with client...
        this.logger.debug('Initialized ServiceA')
    }
}

这是 Redis 服务:

class RedisService {
    constructor(private readonly configService: ConfigService) {}

    async onModuleInit(): Promise<void> {
        ...
        this.logger.log(`Initializing Redis client at ${host}:${port}`)
        this.redis = new Cluster([{ port: port, host: host }], clusterConfig)
    }
}

如您所见,RedisService 也在其 onModuleInit 生命周期方法内部进行了初始化。

我在日志中看到的内容:

[Nest] 41  - 01/08/2023, 10:30:19 AM   DEBUG [ServiceA] Initializing ServiceA...
[Nest] 41  - 01/08/2023, 10:30:19 AM     LOG [RedisService] Initializing Redis client at redis1:7000
// and here I get an error thrown from ServiceA.onModuleInit saying that Redis hasn't been initialized

Nest.js 之前甚至说“ServiceAModule 依赖项已初始化”,但尚未调用 Redis(这是一个依赖项)的 onModuleInit。 为什么?

如何保证onModuleInit的执行顺序?

根据嵌套文档:

onModuleInit():一旦宿主模块的依赖关系被解析后调用。

这并不意味着依赖项已经初始化。

此时你不能确定onModuleInit服务的onModuleInit在 ServiceA 的 onModuleInit 之前运行。

另一方面,最好在您的 Redis controller 中进行new Cluster初始化,以避免您的服务没有定义属性的情况

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM