ProducerStream producing only to single partition

試著忘記壹切 提交于 2020-01-16 08:28:52

问题


I am trying to produce some messages to a single topic having 2 partitions. All the messages are going to partition number 2 only. I would expect that a producer stream would distribute the messages across all partitions.

const kafka = require('kafka-node')
const { Transform } = require('stream');
const _ = require('lodash'); 
const client = new kafka.KafkaClient({ kafkaHost: 'localhost:9092' })
    , streamproducer = new kafka.ProducerStream({kafkaClient: client});

const stdinTransform = new Transform({
  objectMode: true,
  decodeStrings: true,
  transform (text, encoding, callback) {
    let num = parseInt(text);
    let message = { num: num, method: 'two' }
    console.log('pushing message')
    callback(null, {
      topic: 'topic356',
      messages: JSON.stringify(message)
    });
  }
});


stdinTransform.pipe(streamproducer);

function send() {
  var message = new Date().toString();
  stdinTransform.write([{ messages: [message] }]);
}
setInterval(send, 100);

ConsumerGroup:

var consumerOptions = {
  kafkaHost: '127.0.0.1:9092',
  groupId: 'ExampleTestGroup',
  sessionTimeout: 15000,
  protocol: ['roundrobin'],
  fromOffset: 'latest' // equivalent of auto.offset.reset valid values are 'none', 'latest', 'earliest'
};

var topics = 'topic356';

var consumerGroup = new ConsumerGroup(Object.assign({ id: 'consumer1' }, consumerOptions), topics);
consumerGroup.on('data', onMessage);

var consumerGroup2 = new ConsumerGroup(Object.assign({ id: 'consumer2' }, consumerOptions), topics);
consumerGroup2.on('data', onMessage);
consumerGroup2.on('connect', function () {
  setTimeout(function () {
    consumerGroup2.close(true, function (error) {
      console.log('consumer2 closed', error);
    });
  }, 25000);
});

function onMessage (message) {
  console.log(
    ` partition: ${message.partition} `
  );
}

回答1:


Do you produce messages with a key? In Kafka, messages with the same key are published to the same partition.



来源:https://stackoverflow.com/questions/59627078/producerstream-producing-only-to-single-partition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!