最近有一项需求须要把mysql中一个表中的数据同步到es中,分析后使用logstash的jdbc插件获取mysql中的数据,output到es中,采集的状况分两种:开始是全量的采集,以后是增量采集。java
已下式验证的过程:mysql
1.安装logstash和mysqlsql
mysql和logstash的安装就很少说了,能够在网上自行查找。bash
须要注意的事项是:ide
1)可能须要安装:bin/plugin install logstash-input-jdbc测试
2)mysql的driver下载https://cdn.mysql.com//Downloads/Connector-J/mysql-connector-java-5.1.48.tar.gzspa
2.建立mysql表和数据插件
create table test.zy ( id int, str varchar(20) ) ; insert into test.zy values('1','a1'); insert into test.zy values('2','a2'); insert into test.zy values('3','a3'); insert into test.zy values('4','a4'); insert into test.zy values('5','a5'); insert into test.zy values('6','a6'); insert into test.zy values('7','a7'); insert into test.zy values('8','a8'); insert into test.zy values('9','a9'); insert into test.zy values('10','a10'); insert into test.zy values('11','a11'); insert into test.zy values('12','a12'); insert into test.zy values('13','a13'); insert into test.zy values('14','a14'); #增量采集验证插入的数据 insert into test.zy values('15','a15'); insert into test.zy values('16','a16');
3.logstash采集mysql的配置文件3d
#根据字段增量采集 input { jdbc { jdbc_connection_string => "jdbc:mysql://ip:3306/test" jdbc_user => "root" jdbc_password => "123456" jdbc_driver_library => "mysql-connector-java-5.1.36-bin.jar" jdbc_driver_class => "com.mysql.jdbc.Driver" statement => "select * from zy where id > :sql_last_value" use_column_value => true tracking_column => "id" record_last_run => true last_run_metadata_path => "/root/test.log" schedule => "*/2 * * * *" } } output { file { path => "./mysql/test-%{+YYYY-MM-dd}.txt" } } #根据时间戳增量采集 input { jdbc { jdbc_connection_string => "jdbc:mysql://ip:port/test" jdbc_user => "root" jdbc_password => "123456" jdbc_driver_library => "mysql-connector-java-5.1.36-bin.jar" jdbc_driver_class => "com.mysql.jdbc.Driver" jdbc_default_timezone =>"Asia/Shanghai" #设置sql_last_value记录的时间时区,否则会影响增量采集的效果 statement => "select * from zy1 where time > :sql_last_value" use_column_value => false record_last_run => true last_run_metadata_path => "/root/test.log" schedule => "*/2 * * * *" } } output { file { path => "./db2/test-%{+YYYY-MM-dd}.txt" } } input的配置解析 statement 执行myqsl的语句,也能够是statementpath 后跟sql文件的路径 use_column_value 是否使用列值做为依据,进行上次运行位置的记录。 若是设置为true,则使用tracking_column定义的列,做为:sql_last_value. 若是设置为false,则:sql_last_value反映的是上次SQL的运行时间。 tracking_column 增量采集依据的字段名 若是 use_colomn_value为false时,能够不写 record_last_run 是否记录本次采集数据的位置 last_run_metadata_path 设置记录采集数据位置的文件 schedule sql脚本执行的频率
4.采集验证
日志
启动logstash
cd /usr/local/logstash
bin/logstash -f conf/logtash.conf
##logstash 自动加载配置文件 bin/logstash -f conf/logtash.conf --config.reload.automatic
测试logtash是否正常使用
bin/logstash -e 'input { stdin{}} output { output{}}'
测试并退出
bin/logstash -f conf/logtash.conf --config.test_and_exit
logstash采集输出日志:
输出文件内容查看
sql_last_value的记录