如何使用kafka生成器向同一主题发送消息?

时间:2016-06-24 17:13:08

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

我已经设置了生成和使用消息的kafka客户端,当我们将有效负载从生产者发送到主题时,它正如预期的那样工作,所以我现在有生产者的问题第一条消息我能够将它发送到主题,我也能够从kafka主题消费它,现在我尝试发送第二条消息,但消费者没有从kafka主题中读取第二条消息,不知道这里发生了什么?

producer.js

var config = require('./config.js');
var zk = require('node-zookeeper-client');
var kafkaConn = "130.8";
var kafka = require('kafka-node'),
    HighLevelProducer = kafka.HighLevelProducer,
    client = new kafka.Client(kafkaConn),
    producer = new HighLevelProducer(client),
    payloads = [
        { topic: 'test', messages: 'second message' }
    ];
producer.on('ready', function () {
    producer.send(payloads, function (err, data) {
        console.log(data);
    });
});

consumer.js

function start () {
    topics = [{topic: 'test'}];
    var groupId = 'ulogGroup';
    var clientId = "consumer-" + Math.floor(Math.random() * 10000);
    var options = {autoCommit: true, fetchMaxWaitMs: 100, fetchMaxBytes: 10 * 1024 * 1024, groupId: groupId};
    console.log("Started consumer: ", clientId);
    var consumer_client = new kafka.Client(kafkaConn,clientId);
    var client = new Client(consumer_client.connectionString,clientId);
    var consumer = new HighLevelConsumer(client, topics, options);
    console.log("Consumer topics:", getConsumerTopics(consumer).toString());
   // startConsumer(consumer);
    consumer.on('message', function (message) {
        //var topic = message.data;
        console.log('Message',message);
    });
};
start();

1 个答案:

答案 0 :(得分:1)

可能是最简单的建议,但你确定你的第二条消息被发送到kafka队列吗? 与您的消费者一起,您可能希望在生产者正在发布消息时使用内置命令行使用者,以确保您的所有消息都已发布。

bin/kafka-console-consumer.sh --zookeeper host:2181 --topic test --from-beginning