Kafka to ClickHouse with Golang Driver
前言
Base on Teleport 1.0
在之前的文章中我們提到過如果通過Hangout將Kafka中的數據接入ClickHouse中,相關文章。Hangout固然是一個很好的工具,能夠快速的實現將Kafka裏的數據經過處理寫入ClickHouse。但是在clickhouse-jdbc的寫入性能無法滿足我們的預期,clickhouse-jdbc是通過http請求發送數據,無法很好得滿足我們的實時插入需求。
在這種背景下,我們嘗試通過TCP協議來完成數據的寫入。於是我們通過golang實現了Teleport,通過Teleport將數據從Kafka中導入ClickHouse
Teleport
Teleport是由golang編寫的專門用於從Kafka中拉取數據進行處理最後寫入ClickHouse中的ETL工具。其中寫入ClickHouse的部分是通過clickhouse實現的。
接下來還是以Nginx日誌爲例說明如何使用Teleport。
Prerequisites
- 下載Teleport並給予權限
wget https://github.com/RickyHuo/teleport/releases/download/v1.0/teleport
chomd 777 teleport
- 安裝Kafka依賴(librdkafka)
librdkafka.x86_64 0.11.4-1.el7
yum install librdkafka
Configuration Example: Nginx Log
Log Sample
001.cms.msina…sinanode.com
[27/Dec/2017:16:01:03 +0800]
-”GET /n/front/w636h3606893220.jpg/w720q75apl.webp HTTP/1.1”
”SinaNews/201706071542.1 CFNetwork/758.1.6 Darwin/15.0.0”200
[127.0.0.1]-
”-“0.021
10640-
127.0.0.1l.sinaimg.cn
-
Configuration
Input
如下所示, 指定kafka數據源
input:
kafka:
kafka.bootstrap.servers: "localhost:9092"
kafka.group.id: "teleport_nginx_sample"
kafka.auto.offset.reset: "earliest"
topic: "teleport_nginx"
codec: "plain"
Filter
在Filter部分,這裏有一系列轉化的步驟,包括時間轉換、類型轉換等
filter:
- grok:
source_field = "raw_message"
match: "%{NOTSPACE:_hostname}`\[%{HTTPDATE:timestamp}\]`%{NOTSPACE:upstream}`\"%{NOTSPACE:_method}\s%{NOTSPACE:_uri}\s%{NOTSPACE:httpversion}\"`%{QS:_ua}`%{NUMBER:_http_code}`\[%{IP:_remote_addr}\]`%{NOTSPACE:unknow1}`%{QS:_reference}`%{NUMBER:_request_time}`%{NUMBER:_data_size}`%{NOTSPACE:unknow3}`%{IP:_http_x_forwarded_for}`%{NOTSPACE:_domain}`%{DATA:unknow4}$"
- date:
source_field: "timestamp"
format: "02/Jan/2006:15:04:05 -0700"
- add:
idc_ip: "{{Split ._hostname \".\" |Slice 0 2 | Join \".\"}}"
Output
最後我們將處理好的結構化數據寫入ClickHouse
output:
- clickhouse:
table: "cms_msg"
host: "localhost:9000"
clickhouse.read_timeout: 10
clickhouse.write_timeout: 20
clickhouse.debug: "false"
clickhouse.compress: "true"
clickhouse.database: "cms"
fields: ['date', 'datetime','hour', '_hostname', '_domain', '_data_size', '_uri', '_request_time', '_ua', '_http_code', '_remote_addr', '_method', '_reference', '_url', 'idc_ip']
bulk_size: 30000
Global
這裏指定一些全局變量
global:
flush_interval: 20
concurrent: 8
ClickHouse Schema
當然, ClickHouse存儲這些數據的前提是我們已經建立好了這些數據表。具體建表操作如下:
CREATE TABLE cms.cms_msg
(
date Date,
datetime DateTime,
hour Int8,
_uri String,
_url String,
_request_time Float32,
_http_code String,
_hostname String,
_domain String,
_http_x_forwarded_for String,
_remote_addr String,
_reference String,
_data_size Int32,
_method String,
_rs String,
_rs_time Float32,
_ua String,
idc_ip String
) ENGINE = MergeTree(date, (hour, date), 8192)
Running Teleport
./teleport -f conf/grok.yaml
Conclusion
在這篇文章中,我們介紹瞭如何使用Teleport將Nginx日誌文件寫入ClickHouse中,整個配置與Hangout一樣靈活,入手成本不高。目前Teleport支持的插件較少,後期會逐步完善,有任何問題都可以在Teleport中提ISSUE。