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

时间:2019-02-18 18:48:21

标签: node.js apache-kafka kafka-producer-api

在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");
    });

1 个答案:

答案 0 :(得分:0)

在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 ] },
];