在Kafka中,可以使用生產者和消費者來發送和接收消息。
發送消息:
send()
方法來發送消息。在發送消息時,需要指定消息的主題和內容。接收消息:
subscribe()
方法來訂閱一個或多個主題。poll()
方法來輪詢獲取消息。下面是一個簡單的示例代碼,演示了如何發送和接收消息:
發送消息:
import org.apache.kafka.clients.producer.*;
public class ProducerExample {
public static void main(String[] args) {
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 message = "Hello, Kafka!";
ProducerRecord<String, String> record = new ProducerRecord<>(topic, message);
producer.send(record, new Callback() {
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
if (exception != null) {
System.err.println("Failed to send message: " + exception.getMessage());
} else {
System.out.println("Message sent successfully! Offset: " + metadata.offset());
}
}
});
producer.close();
}
}
接收消息:
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.*;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
public class ConsumerExample {
public static void main(String[] args) {
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.ofSeconds(1));
for (ConsumerRecord<String, String> record : records) {
System.out.println("Received message: " + record.value());
}
}
}
}
以上代碼使用Java客戶端實現,你也可以根據自己的需求選擇其他語言或Kafka客戶端庫來發送和接收消息。