import org.apache.kafka.clients.producer.*; 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); String topic = "my-topic"; String key = "my-key"; String value = "Hello Kafka"; ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value); producer.send(record, new Callback() { public void onCompletion(RecordMetadata metadata, Exception e) { if (e != null) { e.printStackTrace(); } else { System.out.println("Message sent successfully: " + metadata); } } }); producer.close(); import org.apache.kafka.clients.consumer.*; Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("group.id", "my-group"); Consumer<String, String> consumer = new KafkaConsumer<>(props); String topic = "my-topic"; consumer.subscribe(Collections.singletonList(topic)); while (true) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord<String, String> record : records) { System.out.println("Received message: " + record.value()); } } consumer.close();


上一篇:
下一篇:
切换中文