1. 程式人生 > >logstash-input-jdbc實現ElasticSearch與mysql同步

logstash-input-jdbc實現ElasticSearch與mysql同步

初步瞭解ES後,想要實現mysql資料同步到ES上。在查詢網上資料後,總結mysql同步到ES一般常用三種方式:

  1. logstash-input-jdbc: ruby語言開發,ES官方推薦
  2. elasticsearch-jdbc: Java開發
  3. go-mysql-elastic:

經過對比後,本來要選擇elasticsearch-jdbc,但費了半天勁後,發現其只支援到ES2.3.4,而我選擇使用的ES版本是最新的5.6.3,所以放棄轉向官方推薦的logstash-input-jdbc。本來看到網上資料感覺這個外掛安裝會特別麻煩,但經過嘗試後,發現並不麻煩,大概是因為logstash5.x之後,集成了logstash-input-jdbc外掛,我們並不需要再下載。

logstash-input-jdbc外掛是logstash 的一個個外掛,我是先安裝logstash,然後使用logstash-input-jdbc。過程如下:

一、logstash安裝

Logstash是一款輕量級的日誌蒐集處理框架,可以方便的把分散的、多樣化的日誌蒐集起來,並進行自定義的處理,然後傳輸到指定的位置,比如某個伺服器或者檔案。

下載地址:https://www.elastic.co/downloads/logstash

下載解壓後,將檔案放置在某一位置即可(免安裝)

測試:

./logstash -e 'input { stdin { } } output { stdout {} }'

出現下圖結果表明成功
這裡寫圖片描述

二、logstash-input-jdbc安裝

文件介紹:
https://www.elastic.co/guide/en/logstash/current/plugins-inputs-jdbc.html
這裡寫圖片描述
Logstash5.x以上版本本身自帶有logstash-input-jdbc,但是根據文件可知,外掛預設沒有繫結,還需安裝,只需要簡單命令列即可。

bin/logstash-plugin install logstash-input-jdbc

這裡寫圖片描述
這個過程會需要等待幾分鐘。

安裝成功後我們可以在logstash根目錄下的以下目錄檢視對應的外掛版本

# cd ../vendor/bundle/jruby/1.9/gems/logstash-input-jdbc-4.2.4

可見logstash-5.6.3對應的jdbc外掛版本是4.2.4。

三、同步測試

logstash 和logstash-input-jdbc都安裝後,和mysql進行同步測試。
首先保證本地有mysql資料庫連線包,mysql-connector-java-x.x.x.jar
然後編寫測試所用配置檔案mysql.conf

input {
    stdin {
    }
    jdbc {
      jdbc_connection_string => "jdbc:mysql://localhost:3306/test?serverTimezone=UTC"
      jdbc_user => "root"
      jdbc_password => "123456"
      jdbc_driver_library => "E:\ES\logstash-5.6.3\mysql-connector-java-6.0.6.jar"
      jdbc_driver_class => "com.mysql.cj.jdbc.Driver"
      jdbc_paging_enabled => "true"
      jdbc_page_size => "50000"
      statement => "select * from user"
      schedule => "* * * * *"
      type => "user"
    }
}

output {
    elasticsearch {
        hosts => "127.0.0.1:9200"
        index => "test"
        document_id => "%{id}"
    }
    stdout {
        codec => json_lines
    }
}

其配置引數在文件中有詳細介紹。
(https://www.elastic.co/guide/en/logstash/current/plugins-inputs-jdbc.html)
這裡寫圖片描述
配置檔案寫完儲存後,繼續命令列

bin/logstash -f config-mysql/mysql.conf

(因為我在bin目錄下新建config-mysq檔案夾了)

配置案例可查閱https://www.elastic.co/guide/en/logstash/current/config-examples.html

如果成功可在命令列視窗看到資料庫中的資料被讀取出來,在瀏覽器sense外掛可查詢到剛剛新增的索引。

GET test/user/_search

這裡寫圖片描述

四、問題

測試過程中遇到的問題有:
1、mysql驅動名異常:

Loading class com.mysql.jdbc.Driver'. This is deprecated. The new
driver class is
com.mysql.cj.jdbc.Driver’. The driver is
automatically registered via the SPI and manual loading of the driver
class is generally unnecessary.

根據提示將原本com.mysql.jdbc.Driver替換成om.mysql.cj.jdbc.Driver
2、mysql The server time zone value 異常:
在專案程式碼-資料庫連線URL後,加上 (注意大小寫必須一致)?serverTimezone=UTC

參考:
https://www.2cto.com/kf/201707/661256.html