實時日誌分析是可觀測體系的核心。本文聚焦 **Flume 採集 → Kafka 緩衝 → Storm 計算** 的經典鏈路,詳細給出生產環境級配置、自定義 Kafka Sink 開發、關鍵參數調優與避坑指南,助你快速落地千萬級日誌實時管道。
# 1. 下載解壓
wget https://archive.apache.org/dist/flume/1.5.2/apache-flume-1.5.2-bin.tar.gz
tar -xzf apache-flume-1.5.2-bin.tar.gz -C /opt/flume
# 2. 配置文件 conf/flume.conf
agent.sources = seqGenSrc
agent.channels = memoryChannel
agent.sinks = loggerSink
# Source: 尾部追蹤日誌文件
agent.sources.seqGenSrc.type = exec
agent.sources.seqGenSrc.command = tail -F /data/mongodata/mongo.log
agent.sources.seqGenSrc.channels = memoryChannel
# Channel: 內存通道 (生產建議 File Channel 持久化)
agent.channels.memoryChannel.type = memory
agent.channels.memoryChannel.capacity = 1000
agent.channels.memoryChannel.transactionCapacity = 100
# Sink: 本地文件滾動 (測試用,生產替換為 Kafka Sink)
agent.sinks.loggerSink.type = file_roll
agent.sinks.loggerSink.sink.directory = /data/flume
agent.sinks.loggerSink.channel = memoryChannel
啟動:
`bin/flume-ng agent --conf conf -f conf/flume.conf -n agent -Dflume.root.logger=INFO,console`
Flume 1.6+ 內建 Kafka Sink,但 1.5.2 仍廣泛使用。需自行實現 `org.apache.flume.sink.kafka.KafkaSink`,核心邏輯在 `process()` 方法:
// 關鍵邏輯節選
public Status process() {
Status status = Status.READY;
Channel ch = getChannel();
Transaction txn = ch.getTransaction();
try {
txn.begin();
Event event = ch.take(); // 批量模式循環 take()
if (event != null) {
byte[] body = event.getBody();
String topic = event.getHeaders().get("topic", defaultTopic);
String key = event.getHeaders().get("key");
// 構建 ProducerRecord (新版 Kafka Producer API)
ProducerRecord record = new ProducerRecord<>(topic, key, body);
producer.send(record, (metadata, exception) -> {
if (exception != null) logger.error("Send failed", exception);
});
}
txn.commit();
return Status.READY;
} catch (Exception ex) {
txn.rollback();
return Status.BACKOFF;
} finally {
txn.close();
}
}
關鍵點:
agent.sinks.kafkaSink.type = org.apache.flume.sink.kafka.KafkaSink
agent.sinks.kafkaSink.brokerList = bigdata-node00:9092
agent.sinks.kafkaSink.requiredAcks = 1
agent.sinks.kafkaSink.batchSize = 100
agent.sinks.kafkaSink.topic = testFlume1
agent.sinks.kafkaSink.channel = memoryChannel
| 組件 | 關鍵參數 | 建議值/策略 |
|---|---|---|
| Flume Source | exec `command` | `tail -F` 斷點續傳;高負載考慮 `spooldir` source (文件輪轉) |
| Flume Channel | type | **File Channel** (持久化、防丟數);內存 Channel 僅測試用 |
| Flume Sink | batchSize | 100-500,配合 Kafka `linger.ms` 批量發送 |
| Kafka Producer | acks, retries, linger.ms | `acks=all`、`retries=3`、`linger.ms=5-10` 微批聚合 |
| Kafka Broker | partition 數 | ≥ 消費者並行度 × 2-3,便於擴容 |
| Storm Spout | max.spout.pending | 控制背壓,防止 Tuple 積壓 OOM |
| 監控 | 指標 | Flume: Channel 填充率、Event 接收/發送速率;Kafka: Lag、吞吐;Storm: 處理延遲、Ack 率 |