一、DataX工具簡介
1、設(shè)計理念
DataX是一個異構(gòu)數(shù)據(jù)源離線同步工具,致力于實現(xiàn)包括關(guān)系型數(shù)據(jù)庫(MySQL、Oracle等)、HDFS、Hive、ODPS、HBase、FTP等各種異構(gòu)數(shù)據(jù)源之間穩(wěn)定高效的數(shù)據(jù)同步功能。解決異構(gòu)數(shù)據(jù)源同步問題,DataX將復(fù)雜的網(wǎng)狀的同步鏈路變成了星型數(shù)據(jù)鏈路,DataX作為中間傳輸載體負(fù)責(zé)連接各種數(shù)據(jù)源。當(dāng)需要接入一個新的數(shù)據(jù)源的時候,只需要將此數(shù)據(jù)源對接到DataX,便能跟已有的數(shù)據(jù)源做到無縫數(shù)據(jù)同步。
絮叨一句:異構(gòu)數(shù)據(jù)源指,為了處理不同種類的業(yè)務(wù),使用不同的數(shù)據(jù)庫系統(tǒng)存儲數(shù)據(jù)。
2、組件結(jié)構(gòu)
DataX本身作為離線數(shù)據(jù)同步框架,采用Framework+plugin架構(gòu)構(gòu)建。將數(shù)據(jù)源讀取和寫入抽象成為Reader和Writer插件,納入到整個同步框架中。
- Reader
Reader為數(shù)據(jù)采集模塊,負(fù)責(zé)讀取采集數(shù)據(jù)源的數(shù)據(jù),將數(shù)據(jù)發(fā)送給Framework。
- Writer
Writer為數(shù)據(jù)寫入模塊,負(fù)責(zé)不斷向Framework取數(shù)據(jù),并將數(shù)據(jù)寫入到目的端。
- Framework
Framework用于連接reader和writer,作為兩者的數(shù)據(jù)傳輸通道,并處理緩沖,流控,并發(fā),數(shù)據(jù)轉(zhuǎn)換等核心技術(shù)問題。
3、架構(gòu)設(shè)計
- Job
DataX完成單個數(shù)據(jù)同步的作業(yè),稱為Job,DataX接受到一個Job之后,將啟動一個進(jìn)程來完成整個作業(yè)同步過程。Job模塊是單個作業(yè)的中樞管理節(jié)點,承擔(dān)了數(shù)據(jù)清理、子任務(wù)切分(將單一作業(yè)計算轉(zhuǎn)化為多個子Task)、TaskGroup管理等功能。
- Split
DataXJob啟動后,會根據(jù)不同的源端切分策略,將Job切分成多個小的Task(子任務(wù)),以便于并發(fā)執(zhí)行。Task便是DataX作業(yè)的最小單元,每一個Task都會負(fù)責(zé)一部分?jǐn)?shù)據(jù)的同步工作。
- Scheduler
切分多個Task之后,Job會調(diào)用Scheduler模塊,根據(jù)配置的并發(fā)數(shù)據(jù)量,將拆分成的Task重新組合,組裝成TaskGroup(任務(wù)組)。
- TaskGroup
每一個TaskGroup負(fù)責(zé)以一定的并發(fā)運行完畢分配好的所有Task,默認(rèn)單個任務(wù)組的并發(fā)數(shù)量為5。每一個Task都由TaskGroup負(fù)責(zé)啟動,Task啟動后,會固定啟動Reader—>Channel—>Writer的線程來完成任務(wù)同步工作。DataX作業(yè)運行起來之后,Job監(jiān)控并等待多個TaskGroup模塊任務(wù)完成,等待所有TaskGroup任務(wù)完成后Job成功退出。否則,異常退出,進(jìn)程退出值非0。
二、環(huán)境安裝
推薦Python2.6+,Jdk1.8+(腦補安裝流程)。
1、Python包下載
# yum -y install wget
# wget https://www.python.org/ftp/python/2.7.15/Python-2.7.15.tgz
# tar -zxvf Python-2.7.15.tgz
2、安裝Python
# yum install gcc openssl-devel bzip2-devel
[root@ctvm01 Python-2.7.15]# ./configure --enable-optimizations
# make altinstall
# python -V
3、DataX安裝
# pwd
/opt/module
# ll
datax
# cd /opt/module/datax/bin
-- 測試環(huán)境是否正確
# python datax.py /opt/module/datax/job/job.json
三、同步任務(wù)
1、同步表創(chuàng)建
-- PostgreSQL
CREATE TABLE sync_user (
id INT NOT NULL,
user_name VARCHAR (32) NOT NULL,
user_age int4 NOT NULL,
CONSTRAINT "sync_user_pkey" PRIMARY KEY ("id")
);
CREATE TABLE data_user (
id INT NOT NULL,
user_name VARCHAR (32) NOT NULL,
user_age int4 NOT NULL,
CONSTRAINT "sync_user_pkey" PRIMARY KEY ("id")
);
2、編寫任務(wù)腳本
[root@ctvm01 job]# pwd
/opt/module/datax/job
[root@ctvm01 job]# vim postgresql_job.json
3、腳本內(nèi)容
{
"job": {
"setting": {
"speed": {
"channel": "3"
}
},
"content": [
{
"reader": {
"name": "postgresqlreader",
"parameter": {
"username": "root01",
"password": "123456",
"column": ["id","user_name","user_age"],
"connection": [
{
"jdbcUrl": ["jdbc:postgresql://192.168.72.131:5432/db_01"],
"table": ["data_user"]
}
]
}
},
"writer": {
"name": "postgresqlwriter",
"parameter": {
"username": "root01",
"password": "123456",
"column": ["id","user_name","user_age"],
"connection": [
{
"jdbcUrl": "jdbc:postgresql://192.168.72.131:5432/db_01",
"table": ["sync_user"]
}
],
"postSql": [],
"preSql": []
}
}
}
]
}
}
4、執(zhí)行腳本
# /opt/module/datax/bin/datax.py /opt/module/datax/job/postgresql_job.json
5、執(zhí)行日志
2020-04-23 18:25:33.404 [job-0] INFO JobContainer -
任務(wù)啟動時刻 : 2020-04-23 18:25:22
任務(wù)結(jié)束時刻 : 2020-04-23 18:25:33
任務(wù)總計耗時 : 10s
任務(wù)平均流量 : 1B/s
記錄寫入速度 : 0rec/s
讀出記錄總數(shù) : 2
讀寫失敗總數(shù) : 0
四、源碼流程分析
注意:這里源碼只貼出核心流程,如果要看完整源碼,可以自行從Git上下載。
1、讀取數(shù)據(jù)
核心入口:PostgresqlReader
啟動讀任務(wù)
public static class Task extends Reader.Task {
@Override
public void startRead(RecordSender recordSender) {
int fetchSize = this.readerSliceConfig.getInt(com.alibaba.datax.plugin.rdbms.reader.Constant.FETCH_SIZE);
this.commonRdbmsReaderSlave.startRead(this.readerSliceConfig, recordSender,
super.getTaskPluginCollector(), fetchSize);
}
}
讀取任務(wù)啟動之后,執(zhí)行讀取數(shù)據(jù)操作。
核心類:CommonRdbmsReader
public void startRead(Configuration readerSliceConfig,
RecordSender recordSender,
TaskPluginCollector taskPluginCollector, int fetchSize) {
ResultSet rs = null;
try {
// 數(shù)據(jù)讀取
rs = DBUtil.query(conn, querySql, fetchSize);
queryPerfRecord.end();
ResultSetMetaData metaData = rs.getMetaData();
columnNumber = metaData.getColumnCount();
PerfRecord allResultPerfRecord = new PerfRecord(taskGroupId, taskId, PerfRecord.PHASE.RESULT_NEXT_ALL);
allResultPerfRecord.start();
long rsNextUsedTime = 0;
long lastTime = System.nanoTime();
// 數(shù)據(jù)傳輸至交換區(qū)
while (rs.next()) {
rsNextUsedTime += (System.nanoTime() - lastTime);
this.transportOneRecord(recordSender, rs,metaData, columnNumber, mandatoryEncoding, taskPluginCollector);
lastTime = System.nanoTime();
}
allResultPerfRecord.end(rsNextUsedTime);
}catch (Exception e) {
throw RdbmsException.asQueryException(this.dataBaseType, e, querySql, table, username);
} finally {
DBUtil.closeDBResources(null, conn);
}
}
2、數(shù)據(jù)傳輸
核心接口:RecordSender(發(fā)送)
public interface RecordSender {
public Record createRecord();
public void sendToWriter(Record record);
public void flush();
public void terminate();
public void shutdown();
}
核心接口:RecordReceiver(接收)
public interface RecordReceiver {
public Record getFromReader();
public void shutdown();
}
核心類:BufferedRecordExchanger
class BufferedRecordExchanger implements RecordSender, RecordReceiver
3、寫入數(shù)據(jù)
核心入口:PostgresqlWriter
啟動寫任務(wù)
public static class Task extends Writer.Task {
public void startWrite(RecordReceiver recordReceiver) {
this.commonRdbmsWriterSlave.startWrite(recordReceiver, this.writerSliceConfig, super.getTaskPluginCollector());
}
}
寫數(shù)據(jù)任務(wù)啟動之后,執(zhí)行數(shù)據(jù)寫入操作。
核心類:CommonRdbmsWriter
public void startWriteWithConnection(RecordReceiver recordReceiver,
Connection connection) {
// 寫數(shù)據(jù)庫的SQL語句
calcWriteRecordSql();
List<Record> writeBuffer = new ArrayList<>(this.batchSize);
int bufferBytes = 0;
try {
Record record;
while ((record = recordReceiver.getFromReader()) != null) {
writeBuffer.add(record);
bufferBytes += record.getMemorySize();
if (writeBuffer.size() >= batchSize || bufferBytes >= batchByteSize) {
doBatchInsert(connection, writeBuffer);
writeBuffer.clear();
bufferBytes = 0;
}
}
if (!writeBuffer.isEmpty()) {
doBatchInsert(connection, writeBuffer);
writeBuffer.clear();
bufferBytes = 0;
}
} catch (Exception e) {
throw DataXException.asDataXException(
DBUtilErrorCode.WRITE_DATA_ERROR, e);
} finally {
writeBuffer.clear();
bufferBytes = 0;
DBUtil.closeDBResources(null, null, connection);
}