0

我正在尝试为具有 2 个分区的单个主题生成一些消息。所有消息都将仅发送到 2 号分区。我希望生产者流将消息分发到所有分区。

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);

消费者组:

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} `
  );
}
4

2 回答 2

0

您是否使用密钥生成消息?在 Kafka 中,具有相同 key 的消息发布到同一个分区。

于 2020-01-08T07:18:25.857 回答
0

在 options 中使用 partitionerType,默认为 0,

分区器类型(默认 = 0,随机 = 1,循环 = 2,键控 = 3,自定义 = 4),默认 0

new kafka.Producer(new kafka.KafkaClient({ kafkaHost: 'localhost:9092' }),{
    partitionerType:1
});

https://github.com/SOHU-Co/kafka-node/issues/1094

于 2020-06-18T06:29:52.993 回答