1. 生产者配置
Properties props = new Properties();
props.put("bootstrap.servers", "kafka1:9092,kafka2: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"); // 0/1/all
props.put("retries", Integer.MAX_VALUE); // 无限重试
props.put("enable.idempotence", true); // 幂等性(默认false)
// 性能
props.put("linger.ms", 5); // 批量等待 5ms
props.put("batch.size", 16384); // 批量大小 16KB
props.put("compression.type", "lz4"); // 压缩算法
Producer<String, String> producer = new KafkaProducer<>(props);
2. ACK 策略
| acks | 行为 | 吞吐 | 可靠性 |
|---|---|---|---|
| 0 | 不等待确认 | 最高 | 可能丢 |
| 1 | 等待 Leader 确认 | 中 | Leader 宕机时丢 |
| all | 等待 ISR 全部确认 | 低 | 不丢 |
3. 发送模式
// 异步发送(推荐)
producer.send(new ProducerRecord<>("orders", orderId, json),
(metadata, exception) -> {
if (exception != null) exception.printStackTrace();
});
// 同步发送
RecordMetadata metadata = producer.send(record).get();
// 带事务的发送(Exactly-Once)
producer.initTransactions();
producer.beginTransaction();
producer.send(record1);
producer.send(record2);
producer.commitTransaction();
4. 分区器
// 默认: murmur2(key) % numPartitions
// 无 key: round-robin
// 自定义:
props.put("partitioner.class", CustomPartitioner.class.getName());
public class CustomPartitioner implements Partitioner {
public int partition(String topic, Object key, byte[] keyBytes,
Object value, byte[] valueBytes, Cluster cluster) {
int numPartitions = cluster.partitionCountForTopic(topic);
// 同一用户的消息到同一分区(保证顺序)
return Math.abs(key.hashCode()) % numPartitions;
}
}
延伸阅读
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。