FlinkCDC全量及增量采集SqlServer数据

本文将详细介绍Flink-CDC如何全量及增量采集Sqlserver数据源,准备适配Sqlserver数据源的小伙伴们可以参考本文,希望本文能给你带来一定的帮助。

一、Sqlserver的安装及开启事务日志

如果没有Sqlserver环境,但你又想学习这块的内容,那你只能自己动手通过docker安装一个 myself sqlserver来用作学习,当然,如果你有现成环境,那就检查一下Sqlserver是否开启了代理(sqlagent.enabled)服务和CDC功能。

1.1 docker拉取镜像

Github上写Flink-CDC 目前支持的Sqlserver版本为2012, 2014, 2016, 2017, 2019,但我想全部拉到最新(事实证明,2022-latest 和latest是一样的,因为imagId都是一致的,且在后续测试也是没有问题的),所以我在docker上拉取镜像时,直接采用如下命令:

docker pull mcr.microsoft.com/mssql/server:latest
1.2 运行Sqlserver并设置代理

标准启动模式,没什么好说的,主要设置一下密码(密码要求比较严格,建议直接在网上搜个随机密码生成器来搞一下)。

docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=${your_password}' \-p 1433:1433 --name sqlserver \-d mcr.microsoft.com/mssql/server:latest

设置代理sqlagent.enabled,代理设置完成后,需要重启Sqlserver,因为我们是docker安装的,直接用docker restart sqlserver就行了。

[root@hdp-01 ~]# docker exec -it --user root sqlserver bash
root@0274812d0c10:/# /opt/mssql/bin/mssql-conf set sqlagent.enabled true
SQL Server needs to be restarted in order to apply this setting. Please run
'systemctl restart mssql-server.service'.
root@0274812d0c10:/# exit
exit
[root@hdp-01 ~]# docker restart sqlserver
sqlserver
1.3 启用CDC功能

按照如下步骤执行命令,如果看到is_cdc_enabled = 1,则说明当前数据库

root@0274812d0c10:/# /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "${your_password}"
1> create databases test;
2> go
1> use test;
2> go
Changed database context to 'test'.
1> EXEC sys.sp_cdc_enable_db;
2> go
1> SELECT is_cdc_enabled FROM sys.databases WHERE name = 'test';
2> go
is_cdc_enabled
--------------1(1 rows affected)
1> CREATE TABLE t_info (id int,order_date date,purchaser int,quantity int,product_id int,PRIMARY KEY ([id]))
2> go
1> 
2> 
3> EXEC sys.sp_cdc_enable_table
4> @source_schema = 'dbo',
5> @source_name   = 't_info',
6> @role_name     = 'cdc_role';
7> go
Update mask evaluation will be disabled in net_changes_function because the CLR configuration option is disabled.
Job 'cdc.zeus_capture' started successfully.
Job 'cdc.zeus_cleanup' started successfully.
1> select * from t_info;
2> go
id          order_date       purchaser   quantity    product_id 
----------- ---------------- ----------- ----------- -----------(0 rows affected)
1.4 检查CDC是否正常开启

用客户端连接Sqlserver,查看test库下的INFORMATION_SCHEMA.TABLES中是否出现TABLE_SCHEMA = cdc的表,如果出现,说明已经成功安装Sqlserver并启用了CDC

1> use test;
2> go
Changed database context to 'test'.
1> select * from INFORMATION_SCHEMA.TABLES;
2> go
TABLE_CATALOG	TABLE_SCHEMA	TABLE_NAME	       TABLE_TYPE
test	            dbo	      user_info	         BASE TABLE
test	            dbo	      systranschemas	   BASE TABLE
test	            cdc	      change_tables	     BASE TABLE
test	            cdc	      ddl_history	       BASE TABLE
test	            cdc	      lsn_time_mapping	 BASE TABLE
test	            cdc	      captured_columns	 BASE TABLE
test	            cdc	      index_columns	     BASE TABLE
test	            dbo	      orders	           BASE TABLE
test	            cdc	      dbo_orders_CT	     BASE TABLE

二、具体实现

2.1 Flik-CDC采集SqlServer主程序

添加依赖包:

        <dependency><groupId>com.ververica</groupId><artifactId>flink-connector-sqlserver-cdc</artifactId><version>3.0.0</version></dependency>

编写主函数:

    public static void main(String[] args) throws Exception {StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();// 设置全局并行度env.setParallelism(1);// 设置时间语义为ProcessingTimeenv.getConfig().setAutoWatermarkInterval(0);// 每隔60s启动一个检查点env.enableCheckpointing(60000, CheckpointingMode.EXACTLY_ONCE);// checkpoint最小间隔env.getCheckpointConfig().setMinPauseBetweenCheckpoints(1000);// checkpoint超时时间env.getCheckpointConfig().setCheckpointTimeout(60000);// 同一时间只允许一个checkpoint// env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);// Flink处理程序被cancel后,会保留Checkpoint数据//   env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);SourceFunction<String> sqlServerSource = SqlServerSource.<String>builder().hostname("localhost").port(1433).username("SA").password("").database("test").tableList("dbo.t_info").startupOptions(StartupOptions.initial()).debeziumProperties(getDebeziumProperties()).deserializer(new CustomerDeserializationSchemaSqlserver()).build();DataStreamSource<String> dataStreamSource = env.addSource(sqlServerSource, "_transaction_log_source");dataStreamSource.print().setParallelism(1);env.execute("sqlserver-cdc-test");}public static Properties getDebeziumProperties() {Properties properties = new Properties();properties.put("converters", "sqlserverDebeziumConverter");properties.put("sqlserverDebeziumConverter.type", "SqlserverDebeziumConverter");properties.put("sqlserverDebeziumConverter.database.type", "sqlserver");// 自定义格式,可选properties.put("sqlserverDebeziumConverter.format.datetime", "yyyy-MM-dd HH:mm:ss");properties.put("sqlserverDebeziumConverter.format.date", "yyyy-MM-dd");properties.put("sqlserverDebeziumConverter.format.time", "HH:mm:ss");return properties;}
2.2 自定义Sqlserver反序列化格式:

Flink-CDC底层技术为debezium,它捕获到Sqlserver数据变更(CRUD)的数据格式如下:

#初始化
Struct{after=Struct{id=1,order_date=2024-01-30,purchaser=1,quantity=100,product_id=1},source=Struct{version=1.9.7.Final,connector=sqlserver,name=sqlserver_transaction_log_source,ts_ms=1706574924473,snapshot=true,db=zeus,schema=dbo,table=orders,commit_lsn=0000002b:00002280:0003},op=r,ts_ms=1706603724432}#新增
Struct{after=Struct{id=12,order_date=2024-01-11,purchaser=6,quantity=233,product_id=63},source=Struct{version=1.9.7.Final,connector=sqlserver,name=sqlserver_transaction_log_source,ts_ms=1706603786187,db=zeus,schema=dbo,table=orders,change_lsn=0000002b:00002480:0002,commit_lsn=0000002b:00002480:0003,event_serial_no=1},op=c,ts_ms=1706603788461}#更新
Struct{before=Struct{id=12,order_date=2024-01-11,purchaser=6,quantity=233,product_id=63},after=Struct{id=12,order_date=2024-01-11,purchaser=8,quantity=233,product_id=63},source=Struct{version=1.9.7.Final,connector=sqlserver,name=sqlserver_transaction_log_source,ts_ms=1706603845603,db=zeus,schema=dbo,table=orders,change_lsn=0000002b:00002500:0002,commit_lsn=0000002b:00002500:0003,event_serial_no=2},op=u,ts_ms=1706603850134}#删除
Struct{before=Struct{id=11,order_date=2024-01-11,purchaser=6,quantity=233,product_id=63},source=Struct{version=1.9.7.Final,connector=sqlserver,name=sqlserver_transaction_log_source,ts_ms=1706603973023,db=zeus,schema=dbo,table=orders,change_lsn=0000002b:000025e8:0002,commit_lsn=0000002b:000025e8:0005,event_serial_no=1},op=d,ts_ms=1706603973859}

因此,可以根据自己需要自定义反序列化格式,将数据按照标准统一数据输出,下面是我自定义的格式,供大家参考:

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.ververica.cdc.debezium.DebeziumDeserializationSchema;
import io.debezium.data.Envelope;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.util.Collector;
import org.apache.kafka.connect.data.Field;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.source.SourceRecord;import java.util.HashMap;
import java.util.Map;public class CustomerDeserializationSchemaSqlserver implements DebeziumDeserializationSchema<String> {private static final long serialVersionUID = -1L;@Overridepublic void deserialize(SourceRecord sourceRecord, Collector collector) {Map<String, Object> resultMap = new HashMap<>();String topic = sourceRecord.topic();String[] split = topic.split("[.]");String database = split[1];String table = split[2];resultMap.put("db", database);resultMap.put("tableName", table);//获取操作类型Envelope.Operation operation = Envelope.operationFor(sourceRecord);//获取数据本身Struct struct = (Struct) sourceRecord.value();Struct after = struct.getStruct("after");Struct before = struct.getStruct("before");String op = operation.name();resultMap.put("op", op);//新增,更新或者初始化if (op.equals(Envelope.Operation.CREATE.name()) || op.equals(Envelope.Operation.READ.name()) || op.equals(Envelope.Operation.UPDATE.name())) {JSONObject afterJson = new JSONObject();if (after != null) {Schema schema = after.schema();for (Field field : schema.fields()) {afterJson.put(field.name(), after.get(field.name()));}resultMap.put("after", afterJson);}}if (op.equals(Envelope.Operation.DELETE.name())) {JSONObject beforeJson = new JSONObject();if (before != null) {Schema schema = before.schema();for (Field field : schema.fields()) {beforeJson.put(field.name(), before.get(field.name()));}resultMap.put("before", beforeJson);}}collector.collect(JSON.toJSONString(resultMap, JSONWriter.Feature.FieldBased, JSONWriter.Feature.LargeObject));}@Overridepublic TypeInformation<String> getProducedType() {return BasicTypeInfo.STRING_TYPE_INFO;}}
2.3 自定义日期格式转换器

debezium会将日期转为5位数字,日期时间转为13位的数字,因此我们需要根据Sqlserver的日期类型转换成标准的时期或者时间格式。Sqlserver的日期类型主要包含以下几种:

字段类型快照类型(jdbc type)cdc类型(jdbc type)
DATEjava.sql.Date(91)java.sql.Date(91)
TIMEjava.sql.Timestamp(92)java.sql.Time(92)
DATETIMEjava.sql.Timestamp(93)java.sql.Timestamp(93)
DATETIME2java.sql.Timestamp(93)java.sql.Timestamp(93)
DATETIMEOFFSETmicrosoft.sql.DateTimeOffset(-155)microsoft.sql.DateTimeOffset(-155)
SMALLDATETIMEjava.sql.Timestamp(93)java.sql.Timestamp(93)
import io.debezium.spi.converter.CustomConverter;
import io.debezium.spi.converter.RelationalColumn;
import org.apache.kafka.connect.data.SchemaBuilder;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Properties;@Sl4j
public class SqlserverDebeziumConverter implements CustomConverter<SchemaBuilder, RelationalColumn> {private static final String DATE_FORMAT = "yyyy-MM-dd";private static final String TIME_FORMAT = "HH:mm:ss";private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";private DateTimeFormatter dateFormatter;private DateTimeFormatter timeFormatter;private DateTimeFormatter datetimeFormatter;private SchemaBuilder schemaBuilder;private String databaseType;private String schemaNamePrefix;@Overridepublic void configure(Properties properties) {// 必填参数:database.type,只支持sqlserverthis.databaseType = properties.getProperty("database.type");// 如果未设置,或者设置的不是mysql、sqlserver,则抛出异常。if (this.databaseType == null || !this.databaseType.equals("sqlserver"))) {throw new IllegalArgumentException("database.type 必须设置为'sqlserver'");}// 选填参数:format.date、format.time、format.datetime。获取时间格式化的格式String dateFormat = properties.getProperty("format.date", DATE_FORMAT);String timeFormat = properties.getProperty("format.time", TIME_FORMAT);String datetimeFormat = properties.getProperty("format.datetime", DATETIME_FORMAT);// 获取自身类的包名+数据库类型为默认schema.nameString className = this.getClass().getName();// 查看是否设置schema.name.prefixthis.schemaNamePrefix = properties.getProperty("schema.name.prefix", className + "." + this.databaseType);// 初始化时间格式化器dateFormatter = DateTimeFormatter.ofPattern(dateFormat);timeFormatter = DateTimeFormatter.ofPattern(timeFormat);datetimeFormatter = DateTimeFormatter.ofPattern(datetimeFormat);}// sqlserver的转换器public void registerSqlserverConverter(String columnType, ConverterRegistration<SchemaBuilder> converterRegistration) {String schemaName = this.schemaNamePrefix + "." + columnType.toLowerCase();schemaBuilder = SchemaBuilder.string().name(schemaName);switch (columnType) {case "DATE":converterRegistration.register(schemaBuilder, value -> {if (value == null) {return null;} else if (value instanceof java.sql.Date) {return dateFormatter.format(((java.sql.Date) value).toLocalDate());} else {return this.failConvert(value, schemaName);}});break;case "TIME":converterRegistration.register(schemaBuilder, value -> {if (value == null) {return null;} else if (value instanceof java.sql.Time) {return timeFormatter.format(((java.sql.Time) value).toLocalTime());} else if (value instanceof java.sql.Timestamp) {return timeFormatter.format(((java.sql.Timestamp) value).toLocalDateTime().toLocalTime());} else {return this.failConvert(value, schemaName);}});break;case "DATETIME":case "DATETIME2":case "SMALLDATETIME":case "DATETIMEOFFSET":converterRegistration.register(schemaBuilder, value -> {if (value == null) {return null;} else if (value instanceof java.sql.Timestamp) {return datetimeFormatter.format(((java.sql.Timestamp) value).toLocalDateTime());} else if (value instanceof microsoft.sql.DateTimeOffset) {microsoft.sql.DateTimeOffset dateTimeOffset = (microsoft.sql.DateTimeOffset) value;return datetimeFormatter.format(dateTimeOffset.getOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC).toLocalDateTime());} else {return this.failConvert(value, schemaName);}});break;default:schemaBuilder = null;break;}}@Overridepublic void converterFor(RelationalColumn relationalColumn, ConverterRegistration<SchemaBuilder> converterRegistration) {// 获取字段类型String columnType = relationalColumn.typeName().toUpperCase();// 根据数据库类型调用不同的转换器if (this.databaseType.equals("sqlserver")) {this.registerSqlserverConverter(columnType, converterRegistration);} else {log.warn("不支持的数据库类型: {}", this.databaseType);schemaBuilder = null;}}private String getClassName(Object value) {if (value == null) {return null;}return value.getClass().getName();}// 类型转换失败时的日志打印private String failConvert(Object value, String type) {String valueClass = this.getClassName(value);String valueString = valueClass == null ? null : value.toString();return valueString;}
}

三、总计

目前Fink-CDC对这种增量采集传统数据库的技术已经封装的很好了,并且官方也给了详细的操作教程,但如果想要深入的学习一项技能,个人觉得还是要从头到尾操作一遍,一方面能够快速的提升自己,另一方面发现问题时,也能从不同的角度来思考解决方案,希望本篇文章能够给大家带来一点帮助。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/671164.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何部署Docker Registry并实现无公网ip远程连接本地镜像仓库

文章目录 1. 部署Docker Registry2. 本地测试推送镜像3. Linux 安装cpolar4. 配置Docker Registry公网访问地址5. 公网远程推送Docker Registry6. 固定Docker Registry公网地址 Docker Registry 本地镜像仓库,简单几步结合cpolar内网穿透工具实现远程pull or push (拉取和推送)…

IPv4的公网地址不够?NAT机制可能是当下最好的解决方案

目录 1.前言 2.介绍 3.NAT机制详解 1.前言 我们都知道IPv4的地址范围是32个字节,这其中还有很多地址是不可用的.比如127.*,这些都是环回地址.那么在网路发展日新月异的今天,互联网设备越来越多,我们该如何解决IP地址不够用的问题呢?目前有一种主流的解决方案,也是大家都在用…

Visual Studio 2022 查看类关系图

这里写自定义目录标题 右键要查看的项目 -“查看”-“查看类图”效果展示&#xff1a; 原文地址 www.cnblogs.com 步骤1&#xff1a;勾选扩展开发 步骤2: 勾选类设计器 右键要查看的项目 -“查看”-“查看类图” 效果展示&#xff1a;

操作系统-02-Ubuntu 常用命令等汇总

Ubuntu Ubuntu是一个开源软件平台&#xff0c;可以在从智能手机、平板电脑和个人电脑到服务器和云端等各种设备上运行。 ubuntu Title: Desktop Ubuntu desktop->command: CtrlAltF2~F6 command->desktop: CtrlAltF7 Login Change to root user $ sudu suLogin to al…

AI嵌入式K210项目(27)-条形码识别

文章目录 前言一、什么是条形码&#xff1f;二、实验准备三、实验过程四、API接口总结 前言 本章介绍基于机器视觉实现条形码识别&#xff0c;主要包含两个过程&#xff0c;首先检测图像中是否有条形码&#xff0c;如果有则框出并打印条形码信息&#xff1b; 一、什么是条形码…

ShardingSphere实现openGauss分布式架构

本文档采用openGauss结合ShardingSphere中间件的架构&#xff0c;实现openGauss数据库分布式OLAP场景的环境部署。 术语说明&#xff1a; 开源数据库引擎&#xff1a;openGauss shardingsphere Proxy&#xff1a;定位为透明化的数据库代理端&#xff0c;提供封装了数据库二进…

示波器的电压怎么和测量的电压不一样,空比增加以后 示波器显示的电压反而降低了?

这两天在调电机&#xff0c;发现我用pwm信号&#xff0c;发送给示波器&#xff0c;但是示波器测量的电压和万用表测量的完全不一样&#xff0c;而有奇怪的现象&#xff0c;空比增加以后 示波器显示的电压反而降低了。 最后发现是通道没有设置&#xff0c;要设置成直流模式 点ch…

解决jupyter notebook主题更改、解决工具栏隐藏的问题

安装主题包 进入对应的环境 conda activate pytorch(环境名字自己根据本地环境换) 输入命令行&#xff0c;下载主题包 pip install --upgrade jupyterthemes输入命令&#xff0c;查看主题 jt -lAvailable Themes:1 chesterish 黑色2 grade3 白灰相间3 gruvboxd 深…

CentOS设置定时任务

CentOS设置定时任务 安装定时任务&#xff1a;cron yum install -y cronie启动 systemctl start crond.service设置开机自启动 systemctl enable crond.service检查定时任务状态 systemctl status crond.service编辑定时任务 crontab -e定时任务配置。例如&#xff1a;在…

为什么免费ip代理不适用于分布式爬虫?

费IP代理通常是一些公开免费提供的IP地址和端口&#xff0c;供用户免费使用。然而&#xff0c;这些免费IP代理并不适用于分布式爬虫的使用&#xff0c;原因如下&#xff1a; 1. 不稳定性 免费IP代理通常是由个人或组织提供的&#xff0c;没有稳定的维护和管理机制。因此&…

docker之程序镜像的制作

目录 一、每种资源的预安装&#xff08;基础&#xff09; 安装 nginx安装 redis 二、dockerfile文件制作&#xff08;基础&#xff09; 打包 redis 镜像 创建镜像制作空间制作dockerfile 打包 nginx 镜像 三、创建组合镜像&#xff08;方式一&#xff09; 生成centos容器并…

补题:leetcode第382场周赛 3022. 给定操作次数内使剩余元素的或值最小

3022. 给定操作次数内使剩余元素的或值最小 - 力扣&#xff08;LeetCode&#xff09; 拆位 n个数进行或运算的结果最小&#xff0c;每次操作可以对相邻的两个数进行与运算&#xff0c;至多进行k次操作 n个数进行或运算&#xff0c;可以对每个数进行拆解&#xff0c;拆解成最小…

SpringBoot全局异常处理,返回http状态码500 或 json

1. 自定义异常 public class SystemException extends RuntimeException{private static final long serialVersionUID 1L;public SystemException(String message){super(message);}public SystemException(Throwable cause){super(cause);}public SystemException(String me…

分享springboot框架的一个开源的本地开发部署教程(若依开源项目开发部署过程分享持续更新二开宝藏项目PostgresSQL数据库版)

1首先介绍下若依项目&#xff1a; 若依是一个基于Spring Boot和Spring Cloud技术栈开发的多租户权限管理系统。该开源项目提供了一套完整的权限管理解决方案&#xff0c;包括用户管理、角色管理、菜单管理、部门管理、岗位管理等功能。 若依项目采用前后端分离的架构&#xf…

[beginCTF 2024] crypto/pwn部分

这个比赛没从开始弄&#xff0c;也没弄到结束&#xff0c;中间有点事出去4天&#xff0c;回来后已经结束&#xff0c;而且也下不了附件&#xff0c;很遗憾。 虽然是新生赛&#xff0c;但也挺难&#xff0c;好些题都不会&#xff0c;仅把一部分作了的记下来&#xff0c;其它等等…

使用代理IP有风险吗?如何安全使用代理IP?

代理IP用途无处不在。它们允许您隐藏真实IP地址&#xff0c;从而实现匿名性和隐私保护。这对于保护个人信息、绕过地理受限的内容或访问特定网站都至关重要。 然而&#xff0c;正如任何技术工具一样&#xff0c;代理IP地址也伴随着潜在的风险和威胁。不法分子可能会滥用代理IP…

Cesium 实战 - 标绘功能系列之画面、多边形(draw polygon)

Cesium 实战 - 标绘功能系列之画面、多边形(draw polygon) 核心代码完整代码在线示例本来想着标绘功能是比较基础的功能,而且网上一搜一堆,就不在教程里放了。 后来觉得,标绘也是项目实战中非常常用的,网上虽然教程挺多,但是由于质量参差不齐,版本各不一致。 本教程系…

ue5 蓝图内修改组件附加的插槽

Target是目标,Parent是要加到哪个骨骼上,socketName是骨骼对应的插槽

【PTA主观题】8-1 文件操作

题目要求 编写函数int input(FILE * fp)&#xff0c;录入学生的信息&#xff0c;自定义录入结束方式&#xff0c;但至少包括学号、姓名、班级、分数和登录密码&#xff0c;并按照学号排序后以二进制方式存入stus.dat&#xff0c;函数返回学生数量&#xff1b;定义函数void enc…

Integer超过-128-127比较问题

Integer超过-128-127比较问题 Testpublic void testEquals() {int int1 12;int int2 12;Integer integer1 new Integer(12);Integer integer2 new Integer(12);Integer integer3 new Integer(127);Integer a1 127; //或者写成Integer a1 Integer.valueOf(127);Integer a…