| 依赖 | kafka-clients(版本与 Broker 兼容) |
|---|---|
| 发送 | send() 异步,返回 Future 或回调 |
| 收尾 | flush() + close() 保证缓冲消息发出 |
最小示例
最小示例
Properties props = new Properties();
props.put("bootstrap.servers", "kafka1:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("acks", "all");
props.put("enable.idempotence", "true");
try (Producer<String, String> producer = new KafkaProducer<>(props)) {
ProducerRecord<String, String> record =
new ProducerRecord<>("orders", "o-1001", "{\"amount\":9.9}");
producer.send(record, (metadata, exception) -> {
if (exception != null) {
System.err.println("send failed: " + exception.getMessage());
}
});
producer.flush();
}生产环境建议在回调里记录失败并接入告警;只依赖自动重试会在超时后丢消息。