摘要
本文主要内容是介绍如何使用kafka-connect进行导入导出数据,文章内容来自于kafka官方文档,对官方文档中一些内容作了简要补充。
简介
向console中写入数据然后再写回到console是非常方便的,但是你可能想从其他的数据源写入数据,然后将数据导出到kafka以外的其他系统,kafka connect 为很多系统提供导入导出数据功能,而不用写任何代码
1、准备数据源
>mkdir /data
> echo -e "foo\nbar" > /data/test.txt
(此处需要注意test.txt文件所在的路径,如果没有/data 文件夹需要先创建他)
2、修改配置文件
之后我们需要修改kafka配置文件 connect-file-source.properties,文件内容相当简单
name=local-file-source
connector.class=FileStreamSource
tasks.max=1
file=/data/test.txt
topic=connect-test
注意修改上述代码中的file字段的值为我们刚才创建的test.txt的文件路径。
修改connect-file-sink.properties配置文件
name=local-file-sink
connector.class=FileStreamSink
tasks.max=1
file=/data/test.sink.txt
topics=connect-test
上述代码中file=/data/test.sink.txt指定导出文件的路径和文件名,topics=connect-test指定topic名称
3、运行Kafka-Connect
配置完成后我们可以运行下面命令进行
> bin/connect-standalone.sh config/connect-standalone.properties config/connect-file-source.properties config/connect-file-sink.properties
1
在输出一系列信息后我们可以查看输出文件
> cat /data/test.sink.txt
foo
bar
查看topic中内容
> bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic connect-test --from-beginning
{"schema":{"type":"string","optional":false},"payload":"foo"}
{"schema":{"type":"string","optional":false},"payload":"bar"}
...
我们向test.txt中新加入一行
> echo "Another line" >> test.txt