以下是一个简单的Java程序,使用Kafka消费者从数据源文件中读取数据并输出:

import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

public class KafkaConsumerExample {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList("test-topic"));

        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
            }
        }
    }
}

在此示例中,我们使用Kafka消费者API创建一个Kafka消费者,然后使用subscribe()方法订阅test-topic主题。然后,我们使用poll()方法从Kafka主题中获取数据,将其打印到控制台上。

请注意,此示例中的消费者将数据打印到控制台,但您可以根据自己的需求修改代码以将数据写入文件或其他目标

java通过kafka消费者读取数据源文件输出

原文地址: https://www.cveoy.top/t/topic/f5pX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录