2

我是 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());
         }
        }
}

先谢谢了。

4

1 回答 1

0

Kafka 生产者在异步模式下为每个代理使用一个 iothread。Kafka Producer - 默认情况下支持多线程?

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

于 2016-01-19T17:04:54.627 回答