当前位置:   article > 正文

Flink CDC2.4 整库实时同步MySql 到Doris_flick mysql doris

flick mysql doris

环境

        Flink 1.15.4 

实现原因

        目前有很多工具都支持无代码实现Mysql -> Doris 的实时同步

        如:SlectDB 已发布的功能包

                Dinky SeaTunnel TIS 等等

         不过好多要么不支持表结构变动,要不不支持多sink,我们的业务必须支持对表结构的实时级变动,因为会对表字段级别的修改,字段类型更改,字段名字更改删除添加等

        所以要支持整库同步且又要表结构的实时变动就要自己写

                

所需jar

        flink-doris-connector-1.15-1.4.0.jar  -- 实现一键万表同步

        flink-sql-connector-mysql-cdc-2.4.0.jar --包含所有相关依赖,无需在导入debezium、cdc等等

流程

        1、脚本创建库表

        2、同步表结构程序  

        3、Flink cdc 程序

对比第一版本:使用 Flink CDC 实现 MySQL 数据,表结构实时入 Apache Doris 效率有所提升

        首次同步时keyby 后开窗聚合导致数据倾斜

        聚合数据有字符串拼接改为JsonArray 避免聚合导致背压,字符串在数据量较大时拼接效率太低

Flink cdc 代码

        1、FlinkSingleSync.scala

        

  1. package com.zbkj.sync
  2. import com.alibaba.fastjson2.{JSON, JSONObject,JSONArray}
  3. import com.ververica.cdc.connectors.mysql.source.MySqlSource
  4. import com.ververica.cdc.connectors.mysql.table.StartupOptions
  5. import com.ververica.cdc.connectors.shaded.org.apache.kafka.connect.json.JsonConverterConfig
  6. import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema
  7. import com.zbkj.util.SinkBuilder.getKafkaSink
  8. import com.zbkj.util._
  9. import org.apache.flink.api.common.eventtime.WatermarkStrategy
  10. import org.apache.flink.api.common.restartstrategy.RestartStrategies
  11. import org.apache.flink.api.java.utils.ParameterTool
  12. import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows
  13. import org.apache.flink.streaming.api.{CheckpointingMode, TimeCharacteristic}
  14. import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
  15. import org.apache.flink.streaming.api.windowing.time.Time
  16. import org.apache.flink.streaming.api.scala._
  17. import java.util.Properties
  18. object FlinkSingleSync {
  19. PropertiesManager.initUtil()
  20. val props: PropertiesUtil = PropertiesManager.getUtil
  21. def main(args: Array[String]): Unit = {
  22. val env = StreamExecutionEnvironment.getExecutionEnvironment
  23. // 并行度
  24. env.setParallelism(props.parallelism)
  25. env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)
  26. val parameters: ParameterTool = ParameterTool.fromArgs(args)
  27. val memberID = parameters.getInt("memberID", 0)
  28. val source = parameters.get("source", "")
  29. val log = parameters.getBoolean("log", true)
  30. if (memberID == 0) {
  31. sys.exit(0)
  32. }
  33. val thisMember = "ttk_member_%d".format(memberID)
  34. val jobName = "Sync Member %d".format(memberID)
  35. val syncTopic = "sync_data_%d".format(memberID)
  36. println(syncTopic)
  37. val sourceFormat = SourceFormat.sourceFormat(source)
  38. env.setParallelism(4)
  39. /**
  40. * checkpoint的相关设置 */
  41. // 启用检查点,指定触发checkpoint的时间间隔(单位:毫秒,默认500毫秒),默认情况是不开启的
  42. env.enableCheckpointing(1000L, CheckpointingMode.EXACTLY_ONCE)
  43. // 设定Checkpoint超时时间,默认为10分钟
  44. env.getCheckpointConfig.setCheckpointTimeout(600000)
  45. /**
  46. * 设置检查点路径 */
  47. env.getCheckpointConfig.setCheckpointStorage("file:///data/flink-checkpoints/sync/%d".format(memberID))
  48. /** 设定两个Checkpoint之间的最小时间间隔,防止出现例如状态数据过大而导致Checkpoint执行时间过长,从而导致Checkpoint积压过多
  49. * 最终Flink应用密切触发Checkpoint操作,会占用了大量计算资源而影响到整个应用的性能(单位:毫秒) */
  50. env.getCheckpointConfig.setMinPauseBetweenCheckpoints(60000)
  51. // 默认情况下,只有一个检查点可以运行
  52. // 根据用户指定的数量可以同时触发多个Checkpoint,进而提升Checkpoint整体的效率
  53. //env.getCheckpointConfig.setMaxConcurrentCheckpoints(2)
  54. /** 外部检查点
  55. * 不会在任务正常停止的过程中清理掉检查点数据,而是会一直保存在外部系统介质中,另外也可以通过从外部检查点中对任务进行恢复 */
  56. env.getCheckpointConfig.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)
  57. // env.getCheckpointConfig.setPreferCheckpointForRecovery(true)
  58. // 设置可以允许的checkpoint失败数
  59. env.getCheckpointConfig.setTolerableCheckpointFailureNumber(3)
  60. //设置可容忍的检查点失败数,默认值为0表示不允许容忍任何检查点失败
  61. env.getCheckpointConfig.setTolerableCheckpointFailureNumber(2)
  62. env.disableOperatorChaining()
  63. /**
  64. * 重启策略的配置
  65. * 重启3次,每次失败后等待10000毫秒
  66. */
  67. env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 30000L))
  68. val dataBaseList = thisMember
  69. var tableList = thisMember + ".*"
  70. if (!log) {
  71. tableList = "lb_crm_customer_log|.*(?<!_log)$"
  72. }
  73. val dorisStreamLoad = new DorisStreamLoad2(props)
  74. // numeric 类型转换
  75. val customConverterConfigs = new java.util.HashMap[String, Object] {
  76. put(JsonConverterConfig.DECIMAL_FORMAT_CONFIG, "numeric")
  77. }
  78. /**
  79. * mysql source for doris */
  80. println(dataBaseList, tableList)
  81. val debeziumProps = new Properties()
  82. debeziumProps.setProperty("debezium.snapshot.mode","never")
  83. val mysqlSource = MySqlSource.builder[String]()
  84. .hostname(sourceFormat.getString("sourceHost"))
  85. .port(sourceFormat.getIntValue("sourcePort"))
  86. .databaseList(dataBaseList)
  87. //^((?!lb_admin_log|lb_bugs).)*$
  88. // lb_admin_log、lb_bugs为不需要同步表
  89. .tableList(props.regular_expression)
  90. .username(sourceFormat.getString("sourceUsername"))
  91. .password(sourceFormat.getString("sourcePassword"))
  92. .debeziumProperties(debeziumProps)
  93. // 全量读取
  94. .startupOptions(StartupOptions.initial())
  95. .includeSchemaChanges(true)
  96. // 发现新表,加入同步任务,需要在tableList中配置
  97. .scanNewlyAddedTableEnabled(true)
  98. .deserializer(new JsonDebeziumDeserializationSchema(false, customConverterConfigs)).build()
  99. val streamSource: DataStream[JSONObject] = env.fromSource(mysqlSource, WatermarkStrategy.noWatermarks(), "MySQL Source")
  100. .map(line => JSON.parseObject(line)).setParallelism(4)
  101. val DDLSqlStream: DataStream[JSONObject] = streamSource.filter(line => !line.containsKey("op")).uid("ddlSqlStream")
  102. val DMLStream: DataStream[JSONObject] = streamSource.filter(line => line.containsKey("op")).uid("dmlStream")
  103. /**
  104. * 首次全量同步时 时间窗口内几乎为一个表数据,此时下面操作会数据倾斜
  105. * 在binLogETLOne 中对表加随机数后缀 使其均匀分布
  106. * 聚合操作之后再将tableName转换为实际表
  107. */
  108. val DMLDataStream = FlinkCDCSyncETL.binLogETLOne(DMLStream)
  109. val keyByDMLDataStream:DataStream[(String, String, String, JSONArray)] = DMLDataStream.keyBy(keys => (keys._1, keys._2, keys._3))
  110. .timeWindow(Time.milliseconds(props.window_time_milliseconds))
  111. .reduce((itemFirst, itemSecond) => (itemFirst._1, itemFirst._2, itemFirst._3,combineJsonArray(itemFirst._4,itemSecond._4)))
  112. .map(line=>(line._1,line._2,line._3.split("-")(0),line._4))
  113. .name("分组聚合").uid("keyBy")
  114. keyByDMLDataStream.addSink(new SinkDoris(dorisStreamLoad)).name("数据写入Doris").uid("SinkDoris").setParallelism(4)
  115. val DDLKafkaSink=getKafkaSink("schema_change")
  116. DDLSqlStream.map(jsObj => jsObj.toJSONString()).sinkTo(DDLKafkaSink).name("同步DDL入Kafka").uid("SinkDDLKafka")
  117. val kafkaSink=getKafkaSink(syncTopic)
  118. keyByDMLDataStream.map(line=>(line._2,line._3,1)).filter(!_._2.endsWith("_sql"))
  119. .keyBy(keys => (keys._1, keys._2))
  120. .window(TumblingProcessingTimeWindows.of(Time.seconds(1))).sum(2)
  121. .map(line =>{
  122. val json = new JSONObject()
  123. json.put("member_id", line._1)
  124. json.put("table", line._2)
  125. json.toJSONString()
  126. }).sinkTo(kafkaSink).name("同步数据库表入Kafka").uid("syncDataTableToKafka")
  127. env.execute(jobName)
  128. }
  129. def combineJsonArray(jsr1:JSONArray,jsr2:JSONArray): JSONArray ={
  130. jsr1.addAll(jsr2)
  131. jsr1
  132. }
  133. }

2.FlinkCDCSyncETL.scala

  1. package com.zbkj.util
  2. import com.alibaba.fastjson2.{JSON, JSONArray, JSONObject}
  3. import org.apache.flink.api.scala.createTypeInformation
  4. import org.apache.flink.streaming.api.scala.DataStream
  5. import java.util.Random
  6. object FlinkCDCSyncETL {
  7. def binLogETLOne(dataStreamSource: DataStream[JSONObject]): DataStream[(String, String, String, JSONArray)] = {
  8. /**
  9. * 根据不同日志类型 匹配load doris方式
  10. */
  11. val tupleData: DataStream[(String, String, String, JSONArray)] = dataStreamSource.map(line => {
  12. var data: JSONObject = new JSONObject()
  13. var jsr: JSONArray = new JSONArray()
  14. var mergeType = "APPEND"
  15. val source = line.getJSONObject("source")
  16. val db = source.getString("db")
  17. val table = source.getString("table")
  18. val op=line.getString("op")
  19. if ("d" == op) {
  20. data = line.getJSONObject("before")
  21. mergeType = "DELETE"
  22. } else if ("u" == op) {
  23. data = line.getJSONObject("after")
  24. mergeType = "APPEND"
  25. } else if ("c" == op) {
  26. data = line.getJSONObject("after")
  27. } else if ("r" == op) {
  28. data = line.getJSONObject("after")
  29. mergeType = "APPEND"
  30. }
  31. jsr.add(data)
  32. Tuple4(mergeType, db, table+ "-" + new Random().nextInt(4), jsr)
  33. })
  34. tupleData
  35. }
  36. }

3.DorisStreamLoad2.scala

  1. package com.zbkj.util
  2. import org.apache.doris.flink.exception.StreamLoadException
  3. import org.apache.doris.flink.sink.HttpPutBuilder
  4. import org.apache.http.client.methods.CloseableHttpResponse
  5. import org.apache.http.entity.StringEntity
  6. import org.apache.http.impl.client.{DefaultRedirectStrategy, HttpClientBuilder, HttpClients}
  7. import org.apache.http.util.EntityUtils
  8. import org.slf4j.{Logger, LoggerFactory}
  9. import java.util.{Properties, UUID}
  10. class DorisStreamLoad2(props: PropertiesUtil) extends Serializable {
  11. private val logger: Logger = LoggerFactory.getLogger(classOf[DorisStreamLoad2])
  12. private lazy val httpClientBuilder: HttpClientBuilder = HttpClients.custom.setRedirectStrategy(new DefaultRedirectStrategy() {
  13. override protected def isRedirectable(method: String): Boolean = {
  14. // If the connection target is FE, you need to deal with 307 redirect。
  15. true
  16. }
  17. })
  18. def loadJson(jsonData: String, mergeType: String, db: String, table: String): Unit = try {
  19. val loadUrlPattern = "http://%s/api/%s/%s/_stream_load?"
  20. val entity = new StringEntity(jsonData, "UTF-8")
  21. val streamLoadProp = new Properties()
  22. streamLoadProp.setProperty("merge_type", mergeType)
  23. streamLoadProp.setProperty("format", "json")
  24. streamLoadProp.setProperty("column_separator", ",")
  25. streamLoadProp.setProperty("line_delimiter", ",")
  26. streamLoadProp.setProperty("strip_outer_array", "true")
  27. streamLoadProp.setProperty("exec_mem_limit", "6442450944")
  28. streamLoadProp.setProperty("strict_mode", "true")
  29. val httpClient = httpClientBuilder.build
  30. val loadUrlStr = String.format(loadUrlPattern, props.doris_load_host, db, table)
  31. try {
  32. val builder = new HttpPutBuilder()
  33. val label = UUID.randomUUID.toString
  34. builder.setUrl(loadUrlStr)
  35. .baseAuth(props.doris_user, props.doris_password)
  36. .addCommonHeader()
  37. .setLabel(label)
  38. .setEntity(entity)
  39. .addProperties(streamLoadProp)
  40. handlePreCommitResponse(httpClient.execute(builder.build()))
  41. }
  42. def handlePreCommitResponse(response: CloseableHttpResponse): Unit = {
  43. val statusCode: Int = response.getStatusLine.getStatusCode
  44. if (statusCode == 200 && response.getEntity != null) {
  45. val loadResult: String = EntityUtils.toString(response.getEntity)
  46. logger.info("load Result {}", loadResult)
  47. } else {
  48. throw new StreamLoadException("stream load error: " + response.getStatusLine.toString)
  49. }
  50. }
  51. }
  52. }

4.SinkDoris.scala

  1. package com.zbkj.util
  2. import com.alibaba.fastjson2.JSONArray
  3. import org.apache.flink.configuration.Configuration
  4. import org.apache.flink.streaming.api.functions.sink.RichSinkFunction
  5. class SinkDoris(dorisStreamLoad:DorisStreamLoad2) extends RichSinkFunction[(String, String, String, JSONArray)] {
  6. override def open(parameters: Configuration): Unit = {}
  7. /**
  8. * 每个元素的插入都要调用一次invoke()方法进行插入操作
  9. */
  10. override def invoke(value:(String, String, String, JSONArray)): Unit = {
  11. dorisStreamLoad.loadJson(value._4.toString,value._1,value._2,value._3)
  12. }
  13. override def close(): Unit = {}
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/398633
推荐阅读
相关标签
  

闽ICP备14008679号