KafkaJava应用主要由Java应用程序与Apache Kafka进行交互来实现。
一、KafkaJava生产者示例
以下实例展示如何创建一个简单的Kafka生产者,向Kafka主题发送消息。
import org.apache.kafka.clients.producer.*; import java.util.Properties; public class SimpleProducer { public static void main(String[] args) { String topicName = "MyTopic"; Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); 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<>(props); for (int i = 0; i < 10; i++){ producer.send(new ProducerRecord<String, String>(topicName, Integer.toString(i), Integer.toString(i))); } System.out.println("Message sent successfully"); producer.close(); } }
二、KafkaJava消费者示例
以下实例展示如何创建一个简单的Kafka消费者。
import org.apache.kafka.clients.consumer.*; import java.util.Arrays; import java.util.Properties; public class SimpleConsumer { public static void main(String[] args) { String topicName = "MyTopic"; Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "test"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props); consumer.subscribe(Arrays.asList(topicName)); 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()); } } } }
三、KafkaJava处理逻辑
在使用Kafka时,消息的处理往往需要自定义逻辑。一般我们会在接收消息和发送消息时进行添加处理逻辑。
同样处理逻辑也可以写在发送或接收消息的时候,例如:
... Converter converter = new ConverterObject(); // 假设你有一个消息转换类 String processedValue = converter.process(record.value()); // 这就是你自定义处理逻辑的结果 ...