简体   繁体   English

如何使用 Nest Js 将消息发送到 Kafka 中的自定义分区

[英]How to send message into custom partition in Kafka with Nest Js

I try to send message into right partition here is my NESTJS Producer Controller我尝试将消息发送到正确的分区这里是我的 NESTJS Producer Controller



 constructor(
    private readonly appService: AppService,
    @Inject('any_name_i_want') private readonly client: ClientKafka,
  ) {}

  async onModuleInit() {
    ['test2'].forEach((key) => this.client.subscribeToResponseOf(`${key}`));
    await this.client.connect();
  }

@Get('kafka-test-with-response')
  async testKafkaWithResponse() {
    const res = await this.client.send('test2', {
      foo: 'bar',
      data: new Date().toString(),
      partition: 1,
    });

    return res;
  }

I try to read in NestJs Document but it's provide link into Kafka website and I've found this in Kafka document我尝试阅读 NestJs 文档,但它提供了 Kafka 网站的链接,我在 Kafka 文档中找到了这个

const producer = kafka.producer()

await producer.connect()
await producer.send({
    topic: 'topic-name',
    messages: [
        { key: 'key1', value: 'hello world', partition: 0 },
        { key: 'key2', value: 'hey hey!', partition: 1 }
    ],
})

After I've check in UI Kafka enter image description here在我签入 UI Kafka 后,在此处输入图像描述

It seems like Producer still send random partition Producer 好像还在发送随机分区

I try to deep down check in typescript send() function but it use any so I'm really not sure how to specify partition in send function我尝试深入检查 typescript send() function 但它使用任何所以我真的不确定如何在发送 function 中指定分区

NestJS does use KafkaJS, so that code section you found is correct, assuming you could get a raw kafkajs client instance. NestJS 确实使用 KafkaJS,因此您找到的代码部分是正确的,假设您可以获得原始的 kafkajs 客户端实例。

Alternatively, Kafka uses the record key to partition each event, and in the NestJS ProducerConfig, you can specify a partitioner instance.或者,Kafka 使用记录键对每个事件进行分区,并且在 NestJS ProducerConfig 中,您可以指定一个分区器实例。 https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L104 https://github.com/nestjs/nest/blob/master/packages/microservices/external/kafka.interface.ts#L104

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

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