在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客户端库来发送和接收消息。