繁体   English   中英

如何将数据发送到Node JS中的多个Kafka主题分区

[英]How to send data to multiple Kafka topic partitions in Node JS

在Node js应用程序中,当我尝试将消息发送到Kafka主题时,所有主题都将移至Partition0。该主题创建了4个分区,并且希望以循环机制进行发布,因此我尝试了多个选项,但没有运气。

有什么办法解决这个问题? 下面是代码片段。

payloads = [
    { topic: 'test-topic', messages: ['TestMessage1', 'TestMessage2', 'TestMessage3', 'TestMessage4']},
];
producer.on('ready', function(){
    producer.send(payloads, function(err, data){
        console.log("Successfully written onto Kafka");
    });

在Kafka中,具有相同密钥的消息被放置在同一分区中。 您可以手动定义分区:

// Force partitioning - default partition is 0
payloads = [ 
    { topic: 'test-topic', messages: ['TestMessage1'], partition: 0 },
    { topic: 'test-topic', messages: ['TestMessage2'], partition: 1 },
    { topic: 'test-topic', messages: ['TestMessage3'], partition: 2 },
    { topic: 'test-topic', messages: ['TestMessage4'], partition: 3 }
];

或为每个消息使用不同的密钥:

payloads = [ 
    { topic: 'test-topic', messages: ['TestMessage1'], key: '1' },
    { topic: 'test-topic', messages: ['TestMessage2'], key: '2' },
    { topic: 'test-topic', messages: ['TestMessage3'], key: '3' },
    { topic: 'test-topic', messages: ['TestMessage4'], key: '4' }
];

// Alternatively, you can use KeyedMessage
km = new KeyedMessage('1', 'TestMessage1'),
km2 = new KeyedMessage('2', 'TestMessage2'),
payloads = [
    { topic: 'test-topic', messages: [ km , km2 ] },
];

暂无
暂无

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

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