一、准备好数据库
1.创建好一张表,添加一些测试数据
2.准备mysql-connector
下载地址为https://dev.mysql.com/downloads/connector/j/ 下载后解压可以得到connector的jar包 。
我把它放在了"/usr/share/logstash/lib/mysql-connector-java-8.0.11.jar"这个目录下。
二、 新建mysql与es交互的配置文件
进入docker logstash容器内
docker exec -it 容器ID /bin/bash
进入pipeline目录下
新建一个xxx.conf文件,内容如下,注意替换内容
input {
jdbc {
#驱动包目录位置
jdbc_driver_library => "../lib/mysql-connector-java-8.0.11.jar"
jdbc_driver_class => "Java::com.mysql.jdbc.Driver"
#连接的数据库地址
jdbc_connection_string => "jdbc:mysql://localhost:3306/数据库名"
jdbc_user => "用户名"
jdbc_password => "密码"
statement => "select * from test_user"
jdbc_paging_enabled => "true"
jdbc_page_size => "50000"
#每分钟同步一次数据
schedule => "* * * * *"
}
}
filter {
}
output {
stdout {
#控制台输出格式
codec => json_lines
}
elasticsearch {
#写入到哪个es
hosts => ["你的es地址:9200"]
#es的索引名称,没有的话会自动创建
index => "831"
#需要关联的数据库中有有一个id字段,对应索引的id号
document_id => "%{id}"
}
}
配置完成,下面来执行看看:
# 执行脚本
../bin/logstash -f xxx.conf
# 发现如下输出如下日志
......
[2020-06-06T14:54:57,659][FATAL][logstash.runner ] Logstash could not be started because there is already another instance using the configured data directory. If you wish to run multiple instances, you must change the "path.data" setting.
[2020-06-06T14:54:57,661][ERROR][org.logstash.Logstash ] java.lang.IllegalStateException: Logstash stopped processing because of an error: (SystemExit) exit
网上找到了报错解决办法:
If you want to run multiple logstash instances, you need to define the path.data either by command,make sure the directory is writable
bin/logstash -f xxx.conf --path.data PATH
创建一个目录mydata
,路径/usr/share/logstash/mydata 重新执行以下命令:
../bin/logstash -f xxx.conf --path.data ../mydata/
稍等片刻之后,看到输出以下日志:
ok,数据同步ok了,我们去kibana查看一下:
已经可以看到刚才查询到的数据了,至此结束;
细心的小伙伴发现ctrl+c退出后就没有执行了:使用这条命令即可
nohup ../bin/logstash -f jdbc.conf --path.data ../mydata/ &
本文章结合以下两篇文章的内容编写: