nest js中的Apache Kafka客户端依赖错误

waxmsbnn  于 12个月前  发布在  Apache
关注(0)|答案(1)|浏览(190)

我在Kafka模块中定义了生产者和消费者代码,并试图在单独的模块中使用,但得到了这个错误:

Error: Nest can't resolve dependencies of the CampaignProducer (?). Please make sure that the argument Client at index [0] is available in the MicroserviceClientModule context.

Potential solutions:
- Is MicroserviceClientModule a valid NestJS module?
- If Client is a provider, is it part of the current MicroserviceClientModule?
- If Client is exported from a separate @Module, is that module imported within MicroserviceClientModule?
  @Module({
    imports: [ /* the Module containing Client */ ]
  })

字符串
Kafka模块代码:

@Module({
    providers: [KafkaService],
    exports: [KafkaService],
})
export class KafkaModule {}


以下是Kafka服务文件代码:

@Injectable()
export class KafkaService implements OnModuleInit {
    private kafka: Kafka;
    private readonly kafkaConfig: KafkaConfig;
    private campaignProducer: CampaignProducer;
    private campaignConsumer: CampaignConsumer;

    constructor() {
        this.kafkaConfig = {
            clientId: 'your-client-id',
            brokers: ['localhost:9092'],
        };
        this.kafka = new Kafka(this.kafkaConfig);
        this.campaignProducer = new CampaignProducer(this.kafka);
        this.campaignConsumer = new CampaignConsumer(this.kafka);
    }

    async onModuleInit(): Promise<void> {
        await this.campaignConsumer.consumeCampaignMessages();
    }

    getCampaignConsumer(): CampaignConsumer {
        return this.campaignConsumer;
    }

    getCampaignProducer(): CampaignProducer {
        return this.campaignProducer;
    }
}


我尝试导入CampaignProducer的模块:

@Module({
    imports: [
        KafkaModule,
    ],
    providers: [
        CampaignProducer,
    ],
})
export class MicroserviceClientModule {}


CampaignProducer类的构造函数代码:

@Injectable()
export class CampaignProducer {
    private producer: Producer;
    private readonly topic = 'campaign-topic';
    private readonly groupId = 'campaign-group';

    constructor(private readonly kafka: Kafka) {
        this.producer = this.kafka.producer();
    }

    async sendCampaignMessage(message: string): Promise<void> {
        await this.producer.connect();
        await this.producer.send({
            topic: this.topic,
            messages: [{ value: message }],
        });
    }
}

jvlzgdj9

jvlzgdj91#

您正在您的MicroserviceClientModule中的客户端注册中设置一个名称?如下所示:

@Module({
  imports: [
    MicroserviceClientModule.register([
      {
        name: 'name you Defined',
        transport: Transport.KAFKA,

字符串
如果是,则需要将此名称注入CampaignProducer中构造函数内的Kafka客户端:

constructor(@Inject('name you defined in the module') private readonly kafka: Kafka) {
    this.producer = this.kafka.producer();
}

相关问题