一、爲flume構建agent
先進去flume下的配文件夾裏面 (此處我的配置文件夾名字爲:myconf) 編寫構建agent的配置文件(命名爲:flume2kafka.conf)
flume2kafka.conf
# 定義這個agent中各組件的名字
a1.sources = r1
a1.sinks = k1
a1.channels = c1
# 描述和配置source組件:r1
a1.sources.r1.type = spooldir
a1.sources.r1.spoolDir = /opt/datas
a1.sources.r1.fileHeader = true
# 描述和配置sink組件:k1
a1.sinks.k1.type = org.apache.flume.sink.kafka.KafkaSink
a1.sinks.k1.kafka.topic = jsonTopic
a1.sinks.k1.kafka.bootstrap.servers = 127.0.0.1:9092
a1.sinks.k1.kafka.flumeBatchSize = 20
a1.sinks.k1.kafka.producer.acks = 1
a1.sinks.k1.kafka.producer.linger.ms = 1
a1.sinks.ki.kafka.producer.compression.type = snappy
# 描述和配置channel組件,此處使用是內存緩存的方式
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100
# 描述和配置source channel sink之間的連接關係
a1.sources.r1.channels = c1
a1.sinks.k1.channel = c1
二、啓動zookeeper
sh zkServer.sh start
三、啓動kafka的producer
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test
四、啓動flume的agent
bin/flume-ng agent -c conf -f 配置文件夾名/配置文件名 -n a1 -Dflume.root.logger=INFO,console
五、啓動kafka的消費者
bin/kafka-server-start.sh config/server.properties
topic 和 配置文件flume2kafka.conf裏的sink組件中的topic一致
這樣就開啓了日誌採集 日誌採集完畢之後 flume會提示 如下圖:
文件會寫入到kafka中 具體路徑是kafka配置文件中server.properties裏面Log Basics的配置 如下圖:
查看文件
數據就寫入上圖文件中
六、遇到的問題
java.lang.IllegalStateException:File name has been re-used with different files. Spooling assumptions violated for /opt/data/hello.txt.COMPLETED跟蹤拋出異常的源碼,SpoolDirectorySource會啓動一個線程輪詢監控目錄下的目標文件,當讀取完該文件(readEvents)之後會對該文件進行重名(rollCurrentFile),當重命名失敗時會拋出IllegalStateException,被SpoolDirectoryRunnable catch重新拋出RuntimeException,導致當前線程退出,從源碼看SpoolDirectoryRunnable是單線程執行的,因此線程結束後,監控目錄下其他文件不再被處理。所以,再新建個 word.txt 文件,flume沒有監聽動作了。
七、正確做法
不要在flume_test文件夾下直接新建文件,寫內容。在其他文件下新建,寫好內容,mv 到flume_test文件夾下。[hadoop@nbdo3 ~]$ cd testdata/
[hadoop@nbdo3 testdata]$ ll
total 4
-rw-rw-r–. 1 hadoop hadoop 71 Mar 10 20:19 hello.txt
[hadoop@nbdo3 testdata]$ cp hello.txt …/data/
[hadoop@nbdo3 testdata]$ echo “123456778” >> world.txt
[hadoop@nbdo3 testdata]$ cp world.txt …/data/
[hadoop@nbdo3 testdata]$