最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin13浏览0评论

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

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

在Node js应用程序中,当我尝试向Kafka主题发送消息时,所有内容都将进入分区0.主题是使用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 ] },
];
发布评论

评论列表(0)

  1. 暂无评论