1、 数据同步策略概述
业务数据是数据仓库的重要数据来源,我们需要每日定时从业务数据库中抽取数据,传输到数据仓库中,之后再对数据进行分析统计。
为保证统计结果的正确性,需要保证数据仓库中的数据与业务数据库是同步的,离线数仓的计算周期通常为天,所以数据同步周期也通常为天,即每天同步一次即可。
数据的同步策略有全量同步和增量同步。
全量同步,就是每天都将业务数据库中的全部数据同步一份到数据仓库,这是保证两侧数据同步的最简单的方式。

增量同步,就是每天只将业务数据中的新增及变化数据同步到数据仓库。采用每日增量同步的表,通常需要在首日先进行一次全量同步。

2、 数据同步策略选择
两种策略都能保证数据仓库和业务数据库的数据同步,那应该如何选择呢?下面对两种策略进行简要对比。
|
同步策略 |
优点 |
缺点 |
|
全量同步 |
逻辑简单 |
在某些情况下效率较低。例如某张表数据量较大,但是每天数据的变化比例很低,若对其采用每日全量同步,则会重复同步和存储大量相同的数据。 |
|
增量同步 |
效率高,无需同步和存储重复数据 |
逻辑复杂,需要将每日的新增及变化数据同原来的数据进行整合,才能使用 |
根据上述对比,可以得出以下结论:
通常情况,业务表数据量比较大,优先考虑增量,数据量比较小,优先考虑全量;具体选择由数仓模型决定,此处暂不详解。
下图为各表同步策略:

3 、数据同步工具概述
数据同步工具种类繁多,大致可分为两类,一类是以DataX、Sqoop为代表的基于Select查询的离线、批量同步工具,另一类是以Maxwell、Canal为代表的基于数据库数据变更日志(例如MySQL的binlog,其会实时记录所有的insert、update以及delete操作)的实时流式同步工具。
全量同步通常使用DataX、Sqoop等基于查询的离线同步工具。而增量同步既可以使用DataX、Sqoop等工具,也可使用Maxwell、Canal等工具,下面对增量同步不同方案进行简要对比。
|
增量同步方案 |
DataX/Sqoop |
Maxwell/Canal |
|
对数据库的要求 |
原理是基于查询,故若想通过select查询获取新增及变化数据,就要求数据表中存在create_time、update_time等字段,然后根据这些字段获取变更数据。 |
要求数据库记录变更操作,例如MySQL需开启binlog。 |
|
数据的中间状态 |
由于是离线批量同步,故若一条数据在一天中变化多次,该方案只能获取最后一个状态,中间状态无法获取。 |
由于是实时获取所有的数据变更操作,所以可以获取变更数据的所有中间状态。 |
本项目中,全量同步采用DataX,增量同步采用Maxwell。
4、 全量表数据同步
4.1、数据通道
全量表数据由DataX从MySQL业务数据库直接同步到HDFS,具体数据流向,如下图所示。

4.2、DataX配置文件
我们需要为每张全量表编写一个DataX的json配置文件,此处以activity_info为例,配置文件内容如下:
{
"job": {
"content": [
{
"reader": {
"name": "mysqlreader",
"parameter": {
"column": [
"id",
"activity_name",
"activity_type",
"activity_desc",
"start_time",
"end_time",
"create_time"
],
"connection": [
{
"jdbcUrl": [
"jdbc:mysql://hadoop102:3306/gmall?useUnicode=true&allowPublicKeyRetrieval=true&characterEncoding=utf-8"
],
"table": [
"activity_info"
]
}
],
"password": "Zan@#2024",
"splitPk": "",
"username": "root"
}
},
"writer": {
"name": "hdfswriter",
"parameter": {
"column": [
{
"name": "id",
"type": "bigint"
},
{
"name": "activity_name",
"type": "string"
},
{
"name": "activity_type",
"type": "string"
},
{
"name": "activity_desc",
"type": "string"
},
{
"name": "start_time",
"type": "string"
},
{
"name": "end_time",
"type": "string"
},
{
"name": "create_time",
"type": "string"
}
],
"compress": "gzip",
"defaultFS": "hdfs://hadoop102:8020",
"fieldDelimiter": "\t",
"fileName": "activity_info",
"fileType": "text",
"path": "${targetdir}",
"writeMode": "truncate"
}
}
}
],
"setting": {
"speed": {
"channel": 1
}
}
}
}
注:由于目标路径包含一层日期,用于对不同天的数据加以区分,故path参数并未写死,需在提交任务时通过参数动态传入,参数名称为targetdir。
4.3、DataX配置文件生成
1)DataX配置文件生成器使用
4.3.1 新建Maven项目

4.3.2、 添加如下依赖
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
<version>5.8.11</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-db</artifactId>
<version>5.8.11</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.31</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<!--指定jar包的入口类,UDF用不到主类,因此不用指定-->
<archive>
<manifest>
<mainClass>com.atguigu.datax.Main</mainClass>
</manifest>
</archive>
<!--将依赖编译到jar包中-->
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<!--配置执行器-->
<execution>
<id>make-assembly</id>
<!--绑定到package执行周期上-->
<phase>package</phase>
<goals>
<!--只运行一次-->
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
4.3.3、 新建com.atguigu.datax.beans.Column类
package com.atguigu.datax.beans;
import java.util.HashMap;
import java.util.Map;
public class Column {
private final String name;
private final String type;
private final String hiveType;
private static final Map<String, String> typeMap = new HashMap<>();
static {
typeMap.put("bigint", "bigint");
typeMap.put("int", "bigint");
typeMap.put("smallint", "bigint");
typeMap.put("tinyint", "bigint");
typeMap.put("double", "double");
typeMap.put("float", "float");
}
public Column(String name, String type) {
this.name = name;
this.type = type;
this.hiveType = typeMap.getOrDefault(type, "string");
}
public String name() {
return name;
}
public String type() {
return type;
}
public String hiveType() {
return hiveType;
}
}
4.3.4、新建com.atguigu.datax.beans.Table类
package com.atguigu.datax.beans;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Table {
private final String tableName;
private final List<Column> columns;
public Table(String tableName) {
this.tableName = tableName;
this.columns = new ArrayList<>();
}
public String name() {
return tableName;
}
public void addColumn(String name, String type) {
columns.add(new Column(name, type));
}
public List<String> getColumnNames() {
return columns.stream().map(Column::name).collect(Collectors.toList());
}
public List<Map<String, String>> getColumnNamesAndTypes() {
List<Map<String, String>> result = new ArrayList<>();
columns.forEach(column -> {
Map<String, String> temp = new HashMap<>();
temp.put("name", column.name());
temp.put("type", column.hiveType());
result.add(temp);
});
return result;
}
}
4.3.5、新建com.atguigu.datax.configuration.Configuration类
package com.atguigu.datax.configuration;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
public class Configuration {
public static String MYSQL_USER;
public static String MYSQL_PASSWORD;
public static String MYSQL_HOST;
public static String MYSQL_PORT;
public static String MYSQL_DATABASE_IMPORT;
public static String MYSQL_DATABASE_EXPORT;
public static String MYSQL_URL_IMPORT;
public static String MYSQL_URL_EXPORT;
public static String MYSQL_TABLES_IMPORT;
public static String MYSQL_TABLES_EXPORT;
public static String IS_SEPERATED_TABLES;
public static String HDFS_URI;
public static String IMPORT_OUT_DIR;
public static String EXPORT_OUT_DIR;
public static String IMPORT_MIGRATION_TYPE = "import";
public static String EXPORT_MIGRATION_TYPE = "export";
static {
Path path = Paths.get("configuration.properties");
Properties configuration = new Properties();
try {
configuration.load(Files.newBufferedReader(path));
MYSQL_USER = configuration.getProperty("mysql.username", "root");
MYSQL_PASSWORD = configuration.getProperty("mysql.password", "000000");
MYSQL_HOST = configuration.getProperty("mysql.host", "hadoop102");
MYSQL_PORT = configuration.getProperty("mysql.port", "3306");
MYSQL_DATABASE_IMPORT = configuration.getProperty("mysql.database.import", "gmall");
MYSQL_DATABASE_EXPORT = configuration.getProperty("mysql.database.export", "gmall");
MYSQL_URL_IMPORT = "jdbc:mysql://" + MYSQL_HOST + ":" + MYSQL_PORT + "/" + MYSQL_DATABASE_IMPORT + "?useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8";
MYSQL_URL_EXPORT = "jdbc:mysql://" + MYSQL_HOST + ":" + MYSQL_PORT + "/" + MYSQL_DATABASE_EXPORT + "?useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8";
MYSQL_TABLES_IMPORT = configuration.getProperty("mysql.tables.import", "");
MYSQL_TABLES_EXPORT = configuration.getProperty("mysql.tables.export", "");
IS_SEPERATED_TABLES = configuration.getProperty("is.seperated.tables", "0");
HDFS_URI = configuration.getProperty("hdfs.uri", "hdfs://hadoop102:8020");
IMPORT_OUT_DIR = configuration.getProperty("import_out_dir");
EXPORT_OUT_DIR = configuration.getProperty("export_out_dir");
} catch (IOException e) {
MYSQL_USER = "root";
MYSQL_PASSWORD = "000000";
MYSQL_HOST = "hadoop102";
MYSQL_PORT = "3306";
MYSQL_DATABASE_IMPORT = "gmall";
MYSQL_DATABASE_EXPORT = "gmall";
MYSQL_URL_IMPORT = "jdbc:mysql://" + MYSQL_HOST + ":" + MYSQL_PORT + "/" + MYSQL_DATABASE_IMPORT + "?useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8";
MYSQL_URL_EXPORT = "jdbc:mysql://" + MYSQL_HOST + ":" + MYSQL_PORT + "/" + MYSQL_DATABASE_EXPORT + "?useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8";
MYSQL_TABLES_IMPORT = "";
MYSQL_TABLES_EXPORT = "";
IS_SEPERATED_TABLES = "0";
HDFS_URI = "hdfs://hadoop102:8020";
IMPORT_OUT_DIR = null;
EXPORT_OUT_DIR = null;
}
}
public static void main(String[] args) {
System.out.println(MYSQL_DATABASE_EXPORT);
}
}
4.3.6、 新建com.atguigu.datax.helper.DataxJsonHelper类
package com.atguigu.datax.helper;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.atguigu.datax.beans.Table;
import com.atguigu.datax.configuration.Configuration;
public class DataxJsonHelper {
// 解析 inputConfig 和 outputConfig 模板
// Hadoop 单点集群
private final JSONObject inputConfig = JSONUtil.parseObj("{\"job\":{\"content\":[{\"reader\":{\"name\":\"mysqlreader\",\"parameter\":{\"column\":[],\"connection\":[{\"jdbcUrl\":[],\"table\":[]}],\"password\":\"\",\"splitPk\":\"\",\"username\":\"\"}},\"writer\":{\"name\":\"hdfswriter\",\"parameter\":{\"column\":[],\"compress\":\"gzip\",\"defaultFS\":\"\",\"fieldDelimiter\":\"\\t\",\"fileName\":\"content\",\"fileType\":\"text\",\"path\":\"${targetdir}\",\"writeMode\":\"truncate\",\"nullFormat\":\"\"}}}],\"setting\":{\"speed\":{\"channel\":1}}}}");
private final JSONObject outputConfig = JSONUtil.parseObj("{\"job\":{\"setting\":{\"speed\":{\"channel\":1}},\"content\":[{\"reader\":{\"name\":\"hdfsreader\",\"parameter\":{\"path\":\"${exportdir}\",\"defaultFS\":\"\",\"column\":[\"*\"],\"fileType\":\"text\",\"encoding\":\"UTF-8\",\"fieldDelimiter\":\"\\t\",\"nullFormat\":\"\\\\N\"}},\"writer\":{\"name\":\"mysqlwriter\",\"parameter\":{\"writeMode\":\"replace\",\"username\":\"\",\"password\":\"\",\"column\":[],\"connection\":[{\"jdbcUrl\":\"\",\"table\":[]}]}}}]}}");
// Hadoop HA 集群
// private final JSONObject inputConfig = JSONUtil.parseObj("{\"job\": {\"content\": [{\"reader\": {\"name\": \"mysqlreader\",\"parameter\": {\"column\": [],\"connection\": [{\"jdbcUrl\": [],\"table\": []}],\"password\": \"\",\"splitPk\": \"\",\"username\": \"\"}},\"writer\": {\"name\": \"hdfswriter\",\"parameter\": {\"column\": [],\"compress\": \"gzip\",\"defaultFS\": \"hdfs://mycluster\",\"dfs.nameservices\": \"mycluster\",\"dfs.ha.namenodes.mycluster\": \"namenode1,namenode2\",\"dfs.namenode.rpc-address.aliDfs.namenode1\": \"hdfs://com.tstzyls-hadoop101:8020\",\"dfs.namenode.rpc-address.aliDfs.namenode2\": \"hdfs://com.tstzyls-hadoop102:8020\",\"dfs.client.failover.proxy.provider.mycluster\": \"org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider\",\"fieldDelimiter\": \"\\t\",\"fileName\": \"content\",\"fileType\": \"text\",\"path\": \"${targetdir}\",\"writeMode\": \"truncate\",\"nullFormat\": \"\"}}}],\"setting\": {\"speed\": {\"channel\": 1}}}}");
// private final JSONObject outputConfig = JSONUtil.parseObj("{\"job\": {\"setting\": {\"speed\": {\"channel\": 1}},\"content\": [{\"reader\": {\"name\": \"hdfsreader\",\"parameter\": {\"path\": \"${exportdir}\",\"defaultFS\": \"\",\"dfs.nameservices\": \"mycluster\",\"dfs.ha.namenodes.mycluster\": \"namenode1,namenode2\",\"dfs.namenode.rpc-address.aliDfs.namenode1\": \"hdfs://com.tstzyls-hadoop101:8020\",\"dfs.namenode.rpc-address.aliDfs.namenode2\": \"hdfs://com.tstzyls-hadoop102:8020\",\"dfs.client.failover.proxy.provider.mycluster\": \"org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider\",\"column\": [\"*\"],\"fileType\": \"text\",\"encoding\": \"UTF-8\",\"fieldDelimiter\": \"\\t\",\"nullFormat\": \"\\\\N\"}},\"writer\": {\"name\": \"mysqlwriter\",\"parameter\": {\"writeMode\": \"replace\",\"username\": \"\",\"password\": \"\",\"column\": [],\"connection\": [{\"jdbcUrl\": [],\"table\": []}]}}}]}}");
public DataxJsonHelper() {
// 获取 Reader 和 Writer 配置
JSONObject mysqlReaderPara = inputConfig.getByPath("job.content[0].reader.parameter", JSONObject.class);
JSONObject hdfsWriterPara = inputConfig.getByPath("job.content[0].writer.parameter", JSONObject.class);
JSONObject hdfsReaderPara = outputConfig.getByPath("job.content[0].reader.parameter", JSONObject.class);
JSONObject mysqlWriterPara = outputConfig.getByPath("job.content[0].writer.parameter", JSONObject.class);
// 设置 DefaultFS
hdfsReaderPara.set("defaultFS", Configuration.HDFS_URI);
hdfsWriterPara.set("defaultFS", Configuration.HDFS_URI);
// 设置 MySQL Username
mysqlReaderPara.set("username", Configuration.MYSQL_USER);
mysqlWriterPara.set("username", Configuration.MYSQL_USER);
// 设置 MySQL Password
mysqlReaderPara.set("password", Configuration.MYSQL_PASSWORD);
mysqlWriterPara.set("password", Configuration.MYSQL_PASSWORD);
// 设置 JDBC URL
mysqlReaderPara.putByPath("connection[0].jdbcUrl[0]", Configuration.MYSQL_URL_IMPORT);
mysqlWriterPara.putByPath("connection[0].jdbcUrl", Configuration.MYSQL_URL_EXPORT);
// 写回Reader和Writer配置
inputConfig.putByPath("job.content[0].reader.parameter", mysqlReaderPara);
inputConfig.putByPath("job.content[0].writer.parameter", hdfsWriterPara);
outputConfig.putByPath("job.content[0].reader.parameter", hdfsReaderPara);
outputConfig.putByPath("job.content[0].writer.parameter", mysqlWriterPara);
}
public void setTableAndColumns(Table table, int index, String migrationType) {
// 设置表名
setTable(table, index, migrationType);
// 设置列名及路径
setColumns(table, migrationType);
}
public void setColumns(Table table, String migrationType) {
if (migrationType.equals("import")) {
// 设置 hdfswriter 文件名
inputConfig.putByPath("job.content[0].writer.parameter.fileName", table.name());
// 设置列名
inputConfig.putByPath("job.content[0].reader.parameter.column", table.getColumnNames());
inputConfig.putByPath("job.content[0].writer.parameter.column", table.getColumnNamesAndTypes());
} else {
// 设置列名
outputConfig.putByPath("job.content[0].writer.parameter.column", table.getColumnNames());
}
}
public void setTable(Table table, int index, String migrationType) {
if (migrationType.equals("import")) {
// 设置表名
inputConfig.putByPath("job.content[0].reader.parameter.connection[0].table[" + index + "]", table.name());
} else {
outputConfig.putByPath("job.content[0].writer.parameter.connection[0].table[" + index + "]", table.name());
}
}
public JSONObject getInputConfig() {
return inputConfig;
}
public JSONObject getOutputConfig() {
return outputConfig;
}
}
4.3.7、 新建com.atguigu.datax.helper.MysqlHelper类
package com.atguigu.datax.helper;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.setting.Setting;
import com.atguigu.datax.beans.Table;
import com.atguigu.datax.configuration.Configuration;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class MysqlHelper {
private final List<Table> tables;
public List<Table> getTables() {
return tables;
}
public MysqlHelper(String url, String database, String mysqlTables) {
tables = new ArrayList<>();
Db db = Db.use(DSFactory.create(
Setting.create()
.set("url", url)
.set("user", Configuration.MYSQL_USER)
.set("pass", Configuration.MYSQL_PASSWORD)
.set("showSql", "false")
.set("showParams", "false")
.set("sqlLevel", "info")
).getDataSource());
// 获取设置的表格,如未设置,查询数据库下面所有表格
if (mysqlTables != null && !"".equals(mysqlTables)) {
for (String mysqlTable : mysqlTables.split(",")) {
tables.add(new Table(mysqlTable));
}
} else {
try {
db.findAll(Entity.create("information_schema.TABLES")
.set("TABLE_SCHEMA", database))
.forEach(entity ->
tables.add(new Table(entity.getStr("TABLE_NAME"))));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
// 获取所有表格的列
for (Table table : tables) {
try {
db.findAll(Entity.create("information_schema.COLUMNS")
.set("TABLE_SCHEMA", database)
.set("TABLE_NAME", table.name())
).stream()
.sorted(Comparator.comparingInt(o -> o.getInt("ORDINAL_POSITION")))
.forEach(entity -> table.addColumn(
entity.getStr("COLUMN_NAME"),
entity.getStr("DATA_TYPE")
));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
4.3.8、 新建com.atguigu.datax.Main类
package com.atguigu.datax;
import cn.hutool.json.JSONUtil;
import com.atguigu.datax.beans.Table;
import com.atguigu.datax.configuration.Configuration;
import com.atguigu.datax.helper.DataxJsonHelper;
import com.atguigu.datax.helper.MysqlHelper;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
// 生成 HDFS 入方向配置文件
if (Configuration.IMPORT_OUT_DIR != null &&
!Configuration.IMPORT_OUT_DIR.equals("")) {
MysqlHelper mysqlHelper = new MysqlHelper(
Configuration.MYSQL_URL_IMPORT,
Configuration.MYSQL_DATABASE_IMPORT,
Configuration.MYSQL_TABLES_IMPORT);
DataxJsonHelper dataxJsonHelper = new DataxJsonHelper();
// 获取迁移操作类型
String migrationType = Configuration.IMPORT_MIGRATION_TYPE;
// 创建父文件夹
Files.createDirectories(Paths.get(Configuration.IMPORT_OUT_DIR));
List<Table> tables = mysqlHelper.getTables();
// 判断传入的表是否为分表,根据判断结果采用不同的处理策略
if (Configuration.IS_SEPERATED_TABLES.equals("1")) {
for (int i = 0; i < tables.size(); i++) {
Table table = tables.get(i);
dataxJsonHelper.setTable(table, i, migrationType);
}
dataxJsonHelper.setColumns(tables.get(0), migrationType);
// 输出最终Json配置
FileWriter inputWriter = new FileWriter(Configuration.IMPORT_OUT_DIR + "/" + Configuration.MYSQL_DATABASE_IMPORT + "." + tables.get(0).name() + ".json");
JSONUtil.toJsonStr(dataxJsonHelper.getInputConfig(), inputWriter);
inputWriter.close();
} else {
for (Table table : tables) {
// 设置表信息
dataxJsonHelper.setTableAndColumns(table, 0, migrationType);
// 输出最终Json配置
FileWriter inputWriter = new FileWriter(Configuration.IMPORT_OUT_DIR + "/" + Configuration.MYSQL_DATABASE_IMPORT + "." + table.name() + ".json");
JSONUtil.toJsonStr(dataxJsonHelper.getInputConfig(), inputWriter);
inputWriter.close();
}
}
}
// 生成 HDFS 出方向配置文件
if (Configuration.EXPORT_OUT_DIR != null &&
!"".equals(Configuration.EXPORT_OUT_DIR)) {
MysqlHelper mysqlHelper = new MysqlHelper(
Configuration.MYSQL_URL_EXPORT,
Configuration.MYSQL_DATABASE_EXPORT,
Configuration.MYSQL_TABLES_EXPORT);
DataxJsonHelper dataxJsonHelper = new DataxJsonHelper();
// 获取迁移操作类型
String migrationType = Configuration.EXPORT_MIGRATION_TYPE;
// 创建父文件夹
Files.createDirectories(Paths.get(Configuration.EXPORT_OUT_DIR));
List<Table> tables = mysqlHelper.getTables();
if (Configuration.IS_SEPERATED_TABLES.equals("1")) {
for (int i = 0; i < tables.size(); i++) {
Table table = tables.get(i);
dataxJsonHelper.setTable(table, i, migrationType);
}
dataxJsonHelper.setColumns(tables.get(0), migrationType);
// 输出最终Json配置
FileWriter outputWriter = new FileWriter(Configuration.EXPORT_OUT_DIR + "/" + Configuration.MYSQL_DATABASE_EXPORT + "." + tables.get(0).name() + ".json");
JSONUtil.toJsonStr(dataxJsonHelper.getOutputConfig(), outputWriter);
outputWriter.close();
}
for (Table table : tables) {
// 设置表信息
dataxJsonHelper.setTableAndColumns(table, 0, migrationType);
// 输出最终Json配置
FileWriter outputWriter = new FileWriter(Configuration.EXPORT_OUT_DIR + "/" + Configuration.MYSQL_DATABASE_EXPORT + "." + table.name() + ".json");
JSONUtil.toJsonStr(dataxJsonHelper.getOutputConfig(), outputWriter);
outputWriter.close();
}
}
}
}
4.4、如何使用
4.4.1、修改配置文件
在项目根目录新建配置文件:configuration.properties
|
key |
default |
description |
|
mysql.username |
root |
MySQL用户名 |
|
mysql.password |
000000 |
MySQL密码 |
|
mysql.host |
hadoop102 |
MySQL所在Host |
|
mysql.port |
3306 |
MySQL端口号 |
|
mysql.database.import |
gmall |
导入HDFS的数据库 |
|
mysql.database.export |
gmall |
从HDFS导出的数据库 |
|
mysql.tables.import |
"" |
需要导入的表,空字符串表示全部导入 |
|
mysql.tables.export |
"" |
需要导出的表,空字符串表示全部导出 |
|
is.seperated.tables |
0 |
是否为分表,0为否 |
|
hdfs.uri |
hdfs://hadoop102:8020 |
HDFS Namenode 地址 |
|
import_out_dir |
null |
导入HDFS的配置文件输出地址 |
|
export_out_dir |
null |
从HDFS导出的配置文件输出地址 |
文件内容如下。
mysql.username=root
mysql.password=000000
mysql.host=hadoop102
mysql.port=3306
mysql.database.import=gmall
mysql.database.export=gmall
mysql.tables.import=
mysql.tables.export=
is.seperated.tables=0
hdfs.uri=hdfs://hadoop102:8020
import_out_dir=d:/output/import
export_out_dir=d:/output/export
4.4.2、 运行
1)执行mvn clean package打包,target目录会生成datax-config-generator-1.0-SNAPSHOT-jar-with-dependencies.jar。和configuration.properties文件一并拷入Linux
2)将生成器上传到服务器的/opt/module/gen_datax_config目录
[shuidi@hadoop102 ~]$ mkdir /opt/module/gen_datax_config
[shuidi@hadoop102 ~]$ cd /opt/module/gen_datax_config
3)上传生成器

4)修改configuration.properties配置
mysql.username=root
mysql.password=Zan@#2024
mysql.host=hadoop102
mysql.port=3306
mysql.database.import=gmall
# mysql.database.export=gmall
mysql.tables.import=activity_info,activity_rule,base_trademark,cart_info,base_category1,base_category2,base_category3,coupon_info,sku_attr_value,sku_sale_attr_value,base_dic,sku_info,base_province,spu_info,base_region,promotion_pos,promotion_refer
# mysql.tables.export=
is.seperated.tables=0
hdfs.uri=hdfs://hadoop102:8020
import_out_dir=/opt/module/datax/job/import
# export_out_dir=
5)执行
[shuidi@hadoop102 gen_datax_config]$ java -jar datax-config-generator-1.0-SNAPSHOT-jar-with-dependencies.jar
6)观察结果
[shuidi@hadoop102 gen_datax_config]$ ll /opt/module/datax/job/import
总用量 68
-rw-rw-r-- 1 shuidi shuidi 991 6月 27 21:45 gmall.activity_info.json
-rw-rw-r-- 1 shuidi shuidi 1131 6月 27 21:45 gmall.activity_rule.json
-rw-rw-r-- 1 shuidi shuidi 763 6月 27 21:45 gmall.base_category1.json
-rw-rw-r-- 1 shuidi shuidi 818 6月 27 21:45 gmall.base_category2.json
-rw-rw-r-- 1 shuidi shuidi 818 6月 27 21:45 gmall.base_category3.json
-rw-rw-r-- 1 shuidi shuidi 824 6月 27 21:45 gmall.base_dic.json
-rw-rw-r-- 1 shuidi shuidi 957 6月 27 21:45 gmall.base_province.json
-rw-rw-r-- 1 shuidi shuidi 771 6月 27 21:45 gmall.base_region.json
-rw-rw-r-- 1 shuidi shuidi 816 6月 27 21:45 gmall.base_trademark.json
-rw-rw-r-- 1 shuidi shuidi 1143 6月 27 21:45 gmall.cart_info.json
-rw-rw-r-- 1 shuidi shuidi 1474 6月 27 21:45 gmall.coupon_info.json
-rw-rw-r-- 1 shuidi shuidi 883 6月 27 21:45 gmall.promotion_pos.json
-rw-rw-r-- 1 shuidi shuidi 777 6月 27 21:45 gmall.promotion_refer.json
-rw-rw-r-- 1 shuidi shuidi 959 6月 27 21:45 gmall.sku_attr_value.json
-rw-rw-r-- 1 shuidi shuidi 1135 6月 27 21:45 gmall.sku_info.json
-rw-rw-r-- 1 shuidi shuidi 1072 6月 27 21:45 gmall.sku_sale_attr_value.json
-rw-rw-r-- 1 shuidi shuidi 908 6月 27 21:45 gmall.spu_info.json
4.5、 测试生成的DataX配置文件
以activity_info为例,测试用脚本生成的配置文件是否可用。
1)创建目标路径
由于DataX同步任务要求目标路径提前存在,故需手动创建路径,当前activity_info表的目标路径应为/origin_data/gmall/db/activity_info_full/2022-06-08。
[shuidi@hadoop102 import]$ hadoop fs -mkdir -p /origin_data/gmall/db/activity_info_full/2022-06-08
2)执行DataX同步命令
[shuidi@hadoop102 import]$ python /opt/module/datax/bin/datax.py -p"-Dtargetdir=/origin_data/gmall/db/activity_info_full/2022-06-08" /opt/module/datax/job/import/gmall.activity_info.json
3)观察同步结果
观察HFDS目标路径是否出现数据。

4.6、 全量表数据同步脚本
为方便使用以及后续的任务调度,此处编写一个全量表数据同步脚本。
1)在~/bin目录创建mysql_to_hdfs_full.sh
[shuidi@hadoop102 ~]$ vim ~/bin/mysql_to_hdfs_full.sh
脚本内容如下
#!/bin/bash
DATAX_HOME=/opt/module/datax
# 如果传入日期则do_date等于传入的日期,否则等于前一天日期
if [ -n "$2" ] ;then
do_date=$2
else
do_date=`date -d "-1 day" +%F`
fi
#处理目标路径,此处的处理逻辑是,如果目标路径不存在,则创建;若存在,则清空,目的是保证同步任务可重复执行
handle_targetdir() {
hadoop fs -test -e $1
if [[ $? -eq 1 ]]; then
echo "路径$1不存在,正在创建......"
hadoop fs -mkdir -p $1
else
echo "路径$1已经存在"
fi
}
#数据同步
import_data() {
datax_config=$1
target_dir=$2
handle_targetdir $target_dir
python $DATAX_HOME/bin/datax.py -p"-Dtargetdir=$target_dir" $datax_config
}
case $1 in
"activity_info")
import_data /opt/module/datax/job/import/gmall.activity_info.json /origin_data/gmall/db/activity_info_full/$do_date
;;
"activity_rule")
import_data /opt/module/datax/job/import/gmall.activity_rule.json /origin_data/gmall/db/activity_rule_full/$do_date
;;
"base_category1")
import_data /opt/module/datax/job/import/gmall.base_category1.json /origin_data/gmall/db/base_category1_full/$do_date
;;
"base_category2")
import_data /opt/module/datax/job/import/gmall.base_category2.json /origin_data/gmall/db/base_category2_full/$do_date
;;
"base_category3")
import_data /opt/module/datax/job/import/gmall.base_category3.json /origin_data/gmall/db/base_category3_full/$do_date
;;
"base_dic")
import_data /opt/module/datax/job/import/gmall.base_dic.json /origin_data/gmall/db/base_dic_full/$do_date
;;
"base_province")
import_data /opt/module/datax/job/import/gmall.base_province.json /origin_data/gmall/db/base_province_full/$do_date
;;
"base_region")
import_data /opt/module/datax/job/import/gmall.base_region.json /origin_data/gmall/db/base_region_full/$do_date
;;
"base_trademark")
import_data /opt/module/datax/job/import/gmall.base_trademark.json /origin_data/gmall/db/base_trademark_full/$do_date
;;
"cart_info")
import_data /opt/module/datax/job/import/gmall.cart_info.json /origin_data/gmall/db/cart_info_full/$do_date
;;
"coupon_info")
import_data /opt/module/datax/job/import/gmall.coupon_info.json /origin_data/gmall/db/coupon_info_full/$do_date
;;
"sku_attr_value")
import_data /opt/module/datax/job/import/gmall.sku_attr_value.json /origin_data/gmall/db/sku_attr_value_full/$do_date
;;
"sku_info")
import_data /opt/module/datax/job/import/gmall.sku_info.json /origin_data/gmall/db/sku_info_full/$do_date
;;
"sku_sale_attr_value")
import_data /opt/module/datax/job/import/gmall.sku_sale_attr_value.json /origin_data/gmall/db/sku_sale_attr_value_full/$do_date
;;
"spu_info")
import_data /opt/module/datax/job/import/gmall.spu_info.json /origin_data/gmall/db/spu_info_full/$do_date
;;
"promotion_pos")
import_data /opt/module/datax/job/import/gmall.promotion_pos.json /origin_data/gmall/db/promotion_pos_full/$do_date
;;
"promotion_refer")
import_data /opt/module/datax/job/import/gmall.promotion_refer.json /origin_data/gmall/db/promotion_refer_full/$do_date
;;
"all")
import_data /opt/module/datax/job/import/gmall.activity_info.json /origin_data/gmall/db/activity_info_full/$do_date
import_data /opt/module/datax/job/import/gmall.activity_rule.json /origin_data/gmall/db/activity_rule_full/$do_date
import_data /opt/module/datax/job/import/gmall.base_category1.json /origin_data/gmall/db/base_category1_full/$do_date
import_data /opt/module/datax/job/import/gmall.base_category2.json /origin_data/gmall/db/base_category2_full/$do_date
import_data /opt/module/datax/job/import/gmall.base_category3.json /origin_data/gmall/db/base_category3_full/$do_date
import_data /opt/module/datax/job/import/gmall.base_dic.json /origin_data/gmall/db/base_dic_full/$do_date
import_data /opt/module/datax/job/import/gmall.base_province.json /origin_data/gmall/db/base_province_full/$do_date
import_data /opt/module/datax/job/import/gmall.base_region.json /origin_data/gmall/db/base_region_full/$do_date
import_data /opt/module/datax/job/import/gmall.base_trademark.json /origin_data/gmall/db/base_trademark_full/$do_date
import_data /opt/module/datax/job/import/gmall.cart_info.json /origin_data/gmall/db/cart_info_full/$do_date
import_data /opt/module/datax/job/import/gmall.coupon_info.json /origin_data/gmall/db/coupon_info_full/$do_date
import_data /opt/module/datax/job/import/gmall.sku_attr_value.json /origin_data/gmall/db/sku_attr_value_full/$do_date
import_data /opt/module/datax/job/import/gmall.sku_info.json /origin_data/gmall/db/sku_info_full/$do_date
import_data /opt/module/datax/job/import/gmall.sku_sale_attr_value.json /origin_data/gmall/db/sku_sale_attr_value_full/$do_date
import_data /opt/module/datax/job/import/gmall.spu_info.json /origin_data/gmall/db/spu_info_full/$do_date
import_data /opt/module/datax/job/import/gmall.promotion_pos.json /origin_data/gmall/db/promotion_pos_full/$do_date
import_data /opt/module/datax/job/import/gmall.promotion_refer.json /origin_data/gmall/db/promotion_refer_full/$do_date
;;
esac
2)为mysql_to_hdfs_full.sh增加执行权限
[shuidi@hadoop102 ~]$ chmod 777 ~/bin/mysql_to_hdfs_full.sh
3)测试同步脚本
[shuidi@hadoop102 ~]$ mysql_to_hdfs_full.sh all 2022-06-08
4)检查同步结果
查看HDFS目表路径是否出现全量表数据,全量表共17张。

5、 增量表数据同步
5.1、 数据通道

5.2、 Flume配置
Flume需要将Kafka中topic_db主题的数据传输到HDFS,故其需选用KafkaSource以及HDFSSink,Channel选用FileChannel。
需要注意的是, HDFSSink需要将不同MySQL业务表的数据写到不同的路径,并且路径中应当包含一层日期,用于区分每天的数据。关键配置如下:

具体数据示例如下:

2)Flume配置实操
(1)创建Flume配置文件
在hadoop104节点的Flume的job目录下创建kafka_to_hdfs_db.conf
[shuidi@hadoop104 flume]$ vim job/kafka_to_hdfs_db.conf
(2)配置文件内容如下
a1.sources = r1
a1.channels = c1
a1.sinks = k1
a1.sources.r1.type = org.apache.flume.source.kafka.KafkaSource
a1.sources.r1.batchSize = 5000
a1.sources.r1.batchDurationMillis = 2000
a1.sources.r1.kafka.bootstrap.servers = hadoop102:9092,hadoop103:9092
a1.sources.r1.kafka.topics = topic_db
a1.sources.r1.kafka.consumer.group.id = flume
a1.sources.r1.setTopicHeader = true
a1.sources.r1.topicHeader = topic
a1.sources.r1.interceptors = i1
a1.sources.r1.interceptors.i1.type = com.atguigu.gmall.flume.interceptor.TimestampAndTableNameInterceptor$Builder
a1.channels.c1.type = file
a1.channels.c1.checkpointDir = /opt/module/flume/checkpoint/behavior2
a1.channels.c1.dataDirs = /opt/module/flume/data/behavior2/
a1.channels.c1.maxFileSize = 2146435071
a1.channels.c1.capacity = 1000000
a1.channels.c1.keep-alive = 6
## sink1
a1.sinks.k1.type = hdfs
a1.sinks.k1.hdfs.path = /origin_data/gmall/db/%{tableName}_inc/%Y-%m-%d
a1.sinks.k1.hdfs.filePrefix = db
a1.sinks.k1.hdfs.round = false
a1.sinks.k1.hdfs.rollInterval = 10
a1.sinks.k1.hdfs.rollSize = 134217728
a1.sinks.k1.hdfs.rollCount = 0
a1.sinks.k1.hdfs.fileType = CompressedStream
a1.sinks.k1.hdfs.codeC = gzip
## 拼装
a1.sources.r1.channels = c1
a1.sinks.k1.channel= c1
(3)编写Flume拦截器
在com.atguigu.gmall.flume.interceptor包下创建TimestampAndTableNameInterceptor类。
package com.atguigu.gmall.flume.interceptor;
import com.alibaba.fastjson.JSONObject;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
public class TimestampAndTableNameInterceptor implements Interceptor {
@Override
public void initialize() {
}
@Override
public Event intercept(Event event) {
Map<String, String> headers = event.getHeaders();
String log = new String(event.getBody(), StandardCharsets.UTF_8);
JSONObject jsonObject = JSONObject.parseObject(log);
Long ts = jsonObject.getLong("ts");
//Maxwell输出的数据中的ts字段时间戳单位为秒,Flume HDFSSink要求单位为毫秒
String timeMills = String.valueOf(ts * 1000);
String tableName = jsonObject.getString("table");
headers.put("timestamp", timeMills);
headers.put("tableName", tableName);
return event;
}
@Override
public List<Event> intercept(List<Event> events) {
for (Event event : events) {
intercept(event);
}
return events;
}
@Override
public void close() {
}
public static class Builder implements Interceptor.Builder {
@Override
public Interceptor build() {
return new TimestampAndTableNameInterceptor ();
}
@Override
public void configure(Context context) {
}
}
}
(3)重新打包

(4)删除hadoop104的/opt/module/flume/lib目录下的gmall-1.0-SNAPSHOT-jar-with-dependencies.jar文件
[shuidi@hadoop104 lib]$ cd /opt/module/flume/lib/
[shuidi@hadoop104 lib]$ rm gmall-1.0-SNAPSHOT-jar-with-dependencies.jar
(5)将打好的包放入到hadoop104的/opt/module/flume/lib文件夹下
[shuidi@hadoop104 lib]$ ls | grep gmall
gmall-1.0-SNAPSHOT-jar-with-dependencies.jar
3)通道测试
(1)启动Zookeeper、Kafka集群及Maxwell
(2)启动hadoop104的Flume
[shuidi@hadoop104 flume]$ bin/flume-ng agent -n a1 -c conf/ -f job/kafka_to_hdfs_db.conf
(3)生成模拟数据
确保Maxwell正在运行,而后生成数据。
[shuidi@hadoop102 bin]$ lg.sh
(4)观察HDFS目标路径

增量表目录出现,数据通道已打通。
(5)数据目标路径的日期说明
仔细观察,会发现目标路径中的日期,并非模拟数据的业务日期,而是当前日期。这是由于Maxwell输出的JSON字符串中的ts字段的值,是数据的变动日期。而真实场景下,数据的业务日期与变动日期应当是一致的。教学环境下需要修改时间戳日期,下文详述。
4)编写Flume启停脚本
为方便使用,此处编写一个Flume的启停脚本。
(1)在hadoop102节点的/home/shuidi/bin目录下创建脚本f3.sh
[shuidi@hadoop102 bin]$ vim f3.sh
在脚本中填写如下内容。
#!/bin/bash
case $1 in
"start")
echo " --------启动 hadoop104 业务数据flume-------"
ssh hadoop104 "nohup /opt/module/flume/bin/flume-ng agent -n a1 -c /opt/module/flume/conf -f /opt/module/flume/job/kafka_to_hdfs_db.conf >/dev/null 2>&1 &"
;;
"stop")
echo " --------停止 hadoop104 业务数据flume-------"
ssh hadoop104 "ps -ef | grep kafka_to_hdfs_db | grep -v grep |awk '{print \$2}' | xargs -n1 kill"
;;
esac
(2)增加脚本执行权限
[shuidi@hadoop102 bin]$ chmod 777 f3.sh
(3)f3启动
[shuidi@hadoop102 module]$ f3.sh start
(4)f3停止
[shuidi@hadoop102 module]$ f3.sh stop
5.3 、Maxwell配置
1)Maxwell时间戳问题

为了让Maxwell时间戳日期与模拟的业务日期保持一致,对Maxwell源码进行改动,增加了mock_date参数,在/opt/module/maxwell/config.properties文件中将该参数的值修改为业务日期即可。
2)补充mock.date参数
配置参数如下。
mock_date=2022-06-08
3)重新启动Maxwell
[shuidi@hadoop102 bin]$ mxw.sh restart
4)重新生成模拟数据
[shuidi@hadoop102 bin]$ lg.sh
5)观察HDFS目标路径日期是否与业务日期保持一致
5.4、 增量表首日全量同步
通常情况下,增量表需要在首日进行一次全量同步,后续每日再进行增量同步,首日全量同步可以使用Maxwell的bootstrap功能,方便起见,下面编写一个增量表首日全量同步脚本。
1)在~/bin目录创建mysql_to_kafka_inc_init.sh
[shuidi@hadoop102 bin]$ vim mysql_to_kafka_inc_init.sh
脚本内容如下
#!/bin/bash
# 该脚本的作用是初始化所有的增量表,只需执行一次
MAXWELL_HOME=/opt/module/maxwell
import_data() {
$MAXWELL_HOME/bin/maxwell-bootstrap --database gmall --table $1 --config $MAXWELL_HOME/config.properties
}
case $1 in
"cart_info")
import_data cart_info
;;
"comment_info")
import_data comment_info
;;
"coupon_use")
import_data coupon_use
;;
"favor_info")
import_data favor_info
;;
"order_detail")
import_data order_detail
;;
"order_detail_activity")
import_data order_detail_activity
;;
"order_detail_coupon")
import_data order_detail_coupon
;;
"order_info")
import_data order_info
;;
"order_refund_info")
import_data order_refund_info
;;
"order_status_log")
import_data order_status_log
;;
"payment_info")
import_data payment_info
;;
"refund_payment")
import_data refund_payment
;;
"user_info")
import_data user_info
;;
"all")
import_data cart_info
import_data comment_info
import_data coupon_use
import_data favor_info
import_data order_detail
import_data order_detail_activity
import_data order_detail_coupon
import_data order_info
import_data order_refund_info
import_data order_status_log
import_data payment_info
import_data refund_payment
import_data user_info
;;
esac
2)为mysql_to_kafka_inc_init.sh增加执行权限
[shuidi@hadoop102 bin]$ chmod 777 ~/bin/mysql_to_kafka_inc_init.sh
3)测试同步脚本
(1)清理历史数据
为方便查看结果,现将HDFS上之前同步的增量表数据删除。
[shuidi@hadoop102 bin]$ hadoop fs -ls /origin_data/gmall/db | grep _inc | awk '{print $8}' | xargs hadoop fs -rm -r -f
(2)执行同步脚本
[shuidi@hadoop102 bin]$ mysql_to_kafka_inc_init.sh all
4)检查同步结果
观察HDFS上是否重新出现增量表数据。
6、采集通道启动/停止脚本
1)在/home/shuidi/bin目录下创建脚本cluster.sh
[shuidi@hadoop102 bin]$ vim cluster.sh
在脚本中填写如下内容。
#!/bin/bash
case $1 in
"start"){
echo ================== 启动 集群 ==================
#启动 Zookeeper集群
zk.sh start
#启动 Hadoop集群
hdp.sh start
#启动 Kafka采集集群
kf.sh start
#启动采集 Flume
f1.sh start
#启动日志消费 Flume
f2.sh start
#启动业务消费 Flume
f3.sh start
#启动 maxwell
mxw.sh start
};;
"stop"){
echo ================== 停止 集群 ==================
#停止 Maxwell
mxw.sh stop
#停止 业务消费Flume
f3.sh stop
#停止 日志消费Flume
f2.sh stop
#停止 日志采集Flume
f1.sh stop
#停止 Kafka采集集群
kf.sh stop
#停止 Hadoop集群
hdp.sh stop
#循环直至 Kafka 集群进程全部停止
kafka_count=$(xcall jps | grep Kafka | wc -l)
while [ $kafka_count -gt 0 ]
do
sleep 1
kafka_count=$(jpsall | grep Kafka | wc -l)
echo "当前未停止的 Kafka 进程数为 $kafka_count"
done
#停止 Zookeeper集群
zk.sh stop
};;
esac
2)增加脚本执行权限
[shuidi@hadoop102 bin]$ chmod 777 cluster.sh
3)cluster集群启动脚本
[shuidi@hadoop102 bin]$ cluster.sh start
4)cluster集群停止脚本
[shuidi@hadoop102 module]$ cluster.sh stop

2482

被折叠的 条评论
为什么被折叠?



