如何在kafka中实现多个生产者和多个消费者

时间:2016-01-19 09:19:56

标签: java apache-kafka kafka-consumer-api kafka-producer-api bigdata

我是kafka的新手,我要求我有很多服务器产生大量的日志,我想创建多个生产者和消费者。

我已经为单个制作人和消费者实施了任何人都可以帮助我理解我将如何创建多个制作人和消费者。

这是我的生产者和消费者代码

生产者: -

public class MessageProducerExample {

    public static void main(String[] args) {

        System.out.println("Hello World");


         Properties props = new Properties();
         props.put("bootstrap.servers", "localhost:9092");
         props.put("acks", "all");
         props.put("retries", 0);
         props.put("batch.size", 16384);
         props.put("linger.ms", 1);
         props.put("buffer.memory", 33554432);
         props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
         props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

         Producer<String, String> producer = new KafkaProducer<String, String>(props);
         for(int i = 0; i < 100; i++)
             producer.send(new ProducerRecord<String, String>("test", "Msg"+Integer.toString(i),"Msg"+Integer.toString(i)));

         producer.close();

    }
}

消费者: -

public class MessageConsumerExample {

    public static void main(String[] args) {

        String topicName = args[0];


         Properties props = new Properties();
         props.put("bootstrap.servers", "localhost:9092");
         props.put("group.id", "test-consumer-group");
         props.put("enable.auto.commit", "true");
         props.put("auto.commit.interval.ms", "1000");
         props.put("session.timeout.ms", "30000");
         props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
         props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
         props.put("auto.offset.reset","earliest");

         System.out.println("TopicName="+topicName);

         KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
         consumer.subscribe(Arrays.asList(topicName));

         while (true) {
             ConsumerRecords<String, String> records = consumer.poll(100);
             System.out.println("records"+records.count());
             for (ConsumerRecord<String, String> record : records)
                 //System.out.println("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value());
                 System.out.println("RECORD_OFFSET"+record.offset()+"RECORD_KEY" +record.key()+"RECORD_VALUE "+record.value());
         }
        }
}

先谢谢。

1 个答案:

答案 0 :(得分:0)

Kafka生产者在异步模式下使用每个代理的iothread。 Kafka Producer - By default supports Multithreading?

对于使用者,您可以创建一个运行消费者实例的线程池。只需确保所有实例都具有相同的使用者组。这里给出了一些例子 - Kafka consumer group