国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

用flink cdc sqlserver 將數(shù)據(jù)實時同步到clickhouse

這篇具有很好參考價值的文章主要介紹了用flink cdc sqlserver 將數(shù)據(jù)實時同步到clickhouse。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

flink cdc 終于支持 sqlserver 了。

現(xiàn)在互聯(lián)網(wǎng)公司用sqlserver的不多,大部分都是一些國企的老舊系統(tǒng)。我們以前同步數(shù)據(jù),都是用datax,但是不能實時同步數(shù)據(jù)?,F(xiàn)在有了flinkcdc,可以實現(xiàn)實時同步了。

1、首先sqlserver版本:要求sqlserver版本為14及以上,也就是SQL Server 2017 版。

2、sqlserver開啟cdc,具體細(xì)節(jié)可以百度,有一點(diǎn)要注意,必須啟動SQL Server 代理服務(wù)。

3、需要實現(xiàn)一個json解析方法,用于將同步過來的json數(shù)據(jù)解析出來,并insert到目標(biāo)數(shù)據(jù)庫

4、如果需要斷點(diǎn)續(xù)傳,需要設(shè)置ck,由于我們這邊設(shè)備有限。使用的是RocksDBStateBackend,把數(shù)據(jù)保存到本地了。如果有大數(shù)據(jù)環(huán)境,建議使用FsStateBackend(文件系統(tǒng)狀態(tài)后端 hdfs),將數(shù)據(jù)保存到hdfs

5、關(guān)于維表關(guān)聯(lián)問題,我將維表數(shù)據(jù)放到了redis中?

下面是代碼:

1、pom.xml

<properties>
    <flink.version>1.13.5</flink.version>
    <scala.version>2.11</scala.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-table-planner_2.11</artifactId>
        <version>${flink.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-table-planner-blink_2.11</artifactId>
        <version>${flink.version}</version>
    </dependency>

    <dependency>
        <groupId>com.ververica</groupId>
        <artifactId>flink-connector-sqlserver-cdc</artifactId>
        <!-- The dependency is available only for stable releases, SNAPSHOT dependency need build by yourself. -->
        <version>2.3-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-java_2.11</artifactId>
        <version>${flink.version}</version>
        <!--            <scope>provided</scope>-->
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-scala_2.11</artifactId>
        <version>${flink.version}</version>
        <!--            <scope>provided</scope>-->
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-runtime-web_2.11</artifactId>
        <version>${flink.version}</version>
        <!--            <scope>provided</scope>-->
    </dependency>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-statebackend-rocksdb_2.11</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.7</version>
    </dependency>


    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
    </dependency>

    <dependency>
        <groupId>ru.yandex.clickhouse</groupId>
        <artifactId>clickhouse-jdbc</artifactId>
        <version>0.2.6</version>
    </dependency>


    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-connector-kafka_2.11</artifactId>
        <version>${flink.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>2.7.0</version>
    </dependency>

</dependencies>

2、

package com.cmei.s2c;

import com.ververica.cdc.connectors.sqlserver.SqlServerSource;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.contrib.streaming.state.RocksDBStateBackend;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;


public class SqlServerSourceExample {

    public static void main(String[] args) throws Exception {
        SourceFunction<String> sourceFunction = SqlServerSource.<String>builder()
                .hostname("192.168.10.134")
                .port(1433)
                .database("inventory") // monitor sqlserver database
                .tableList("dbo.products") // monitor products table
                .username("sa")
                .password("qwe123==")
                .deserializer(new JsonDebeziumDeserializationSchema()) // converts SourceRecord to JSON String
                .build();
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);
        //2.Flink-CDC將讀取binlog的位置信息以狀態(tài)的方式保存在CK,如果想要做到斷點(diǎn)續(xù)傳,需要從Checkpoint或者Savepoint啟動程序
        //2.1 開啟Checkpoint,每隔5秒鐘做一次CK
        env.enableCheckpointing(5000L);
        //2.2 指定CK的一致性語義
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        //2.3 設(shè)置任務(wù)關(guān)閉的時候保留最后一次CK數(shù)據(jù)
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 指定從CK自動重啟策略
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 2000L));
        //2.5 設(shè)置狀態(tài)后端
        env.setStateBackend(new RocksDBStateBackend("file:///usr/local/flink-1.13.5/ck"));
        //env.setStateBackend(new MemoryStateBackend());
        // MemoryStateBackend(內(nèi)存狀態(tài)后端)
        // FsStateBackend(文件系統(tǒng)狀態(tài)后端 hdfs)
        // RocksDBStateBackend(RocksDB狀態(tài)后端)
        //env.setStateBackend(new FsStateBackend("hdfs://sc2:8020/flinkCDC"));
        //2.6 設(shè)置訪問HDFS的用戶名
        //System.setProperty("HADOOP_USER_NAME", "root");

        env.addSource(sourceFunction).addSink(new ClickHouseSink()).setParallelism(1);
        //env.addSource(sourceFunction).print().setParallelism(1); // use parallelism 1 for sink to keep message ordering

        env.execute("1");

    }
}

3、json解析

package com.cmei.s2c;

import com.google.gson.Gson;
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;

public class JsonDebeziumDeserializationSchema implements DebeziumDeserializationSchema {

    @Override
    public void deserialize(SourceRecord sourceRecord, Collector collector) throws Exception {
        HashMap<String, Object> hashMap = new HashMap<>();

        String topic = sourceRecord.topic();
        String[] split = topic.split("[.]");
        String database = split[1];
        String table = split[2];
        hashMap.put("database",database);
        hashMap.put("table",table);

        //獲取操作類型
        Envelope.Operation operation = Envelope.operationFor(sourceRecord);
        //獲取數(shù)據(jù)本身
        Struct struct = (Struct)sourceRecord.value();
        Struct after = struct.getStruct("after");
        Struct before = struct.getStruct("before");
        /*
            1,同時存在 beforeStruct 跟 afterStruct數(shù)據(jù)的話,就代表是update的數(shù)據(jù)
             2,只存在 beforeStruct 就是delete數(shù)據(jù)
             3,只存在 afterStruct數(shù)據(jù) 就是insert數(shù)據(jù)
        */

        if (after != null) {
            //insert
            Schema schema = after.schema();
            HashMap<String, Object> hm = new HashMap<>();
            for (Field field : schema.fields()) {
                hm.put(field.name(), after.get(field.name()));
            }
            hashMap.put("data",hm);
        }else if (before !=null){
            //delete
            Schema schema = before.schema();
            HashMap<String, Object> hm = new HashMap<>();
            for (Field field : schema.fields()) {
                hm.put(field.name(), before.get(field.name()));
            }
            hashMap.put("data",hm);
        }else if(before !=null && after !=null){
            //update
            Schema schema = after.schema();
            HashMap<String, Object> hm = new HashMap<>();
            for (Field field : schema.fields()) {
                hm.put(field.name(), after.get(field.name()));
            }
            hashMap.put("data",hm);
        }

        String type = operation.toString().toLowerCase();
        if ("create".equals(type)) {
            type = "insert";
        }else if("delete".equals(type)) {
            type = "delete";
        }else if("update".equals(type)) {
            type = "update";
        }

        hashMap.put("type",type);

        Gson gson = new Gson();
        collector.collect(gson.toJson(hashMap));

    }

    @Override
    public TypeInformation<String> getProducedType() {
        return  BasicTypeInfo.STRING_TYPE_INFO;
    }
}

4、clickhousesink,只實現(xiàn)了insert其他可以自己補(bǔ)全

package com.cmei.s2c;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;

public class ClickHouseSink extends RichSinkFunction<String> {

    Connection connection;

    PreparedStatement pstmt;
    PreparedStatement iStmt;
    PreparedStatement dStmt;
    PreparedStatement uStmt;
    private Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
            String url = "jdbc:clickhouse://192.168.10.61:8123/drugdb";
            conn = DriverManager.getConnection(url,"bigdata","bigdata");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }


    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        connection = getConnection();
        String insertSql = "insert into product(id,name,description,weight) values (?,?,?,?)";
        String deleteSql = "delete from product where id=?";
        String updateSql = "update product set name=? ,description=?,weight=? where id=?";
        iStmt = connection.prepareStatement(insertSql);
        dStmt = connection.prepareStatement(deleteSql);
        uStmt = connection.prepareStatement(updateSql);

    }

    // 每條記錄插入時調(diào)用一次
    public void invoke(String value, Context context) throws Exception {

        Gson t = new Gson();
        HashMap<String, Object> hs = t.fromJson(value, HashMap.class);

        LinkedTreeMap<String,Object> source = (LinkedTreeMap<String,Object>)hs.get("source");
        String database = (String) source.get("db");
        String table = (String) source.get("table");
        String op = (String) hs.get("op");
        /**
         * {"before":null,
         * "after":{"id":109,"name":"spare tire","description":"24 inch spare tire","weight":22.2},
         * "source":{"version":"1.5.4.Final","connector":"sqlserver","name":"sqlserver_transaction_log_source","ts_ms":1648776173094,"snapshot":"last","db":"inventory","sequence":null,"schema":"dbo","table":"products","change_lsn":null,"commit_lsn":"0000002c:00001a60:0001","event_serial_no":null},
         * "op":"r","ts_ms":1648776173094,"transaction":null}*/

        //實現(xiàn)insert方法
        if ("inventory".equals(database) && "products".equals(table)) {
            if ("r".equals(op) || "c".equals(op)) {
                LinkedTreeMap<String, Object> data = (LinkedTreeMap<String, Object>) hs.get("after");
                Double ids = (Double)data.get("id");
                int id =  ids.intValue();
                String name = (String) data.get("name");
                String description = (String) data.get("description");
                Double weights = (Double)data.get("weight");
                float weight=0;
                if("".equals(weights) || weights != null ){
                    weight =  weights.floatValue();
                }

                iStmt.setInt(1, id);
                iStmt.setString(2, name);
                iStmt.setString(3, description);
                iStmt.setFloat(4, weight);

                iStmt.executeUpdate();
            }

//            else if ("d".equals(type)) {
//                System.out.println("delete => " + value);
//                LinkedTreeMap<String, Object> data = (LinkedTreeMap<String, Object>) hs.get("data");
//                String id = (String) data.get("ID");
//                dStmt.setString(1, id);
//                dStmt.executeUpdate();
//            }
//            else if ("u".equals(type)) {
//                System.out.println("update => " + value);
//                LinkedTreeMap<String, Object> data = (LinkedTreeMap<String, Object>) hs.get("data");
//                String id = (String) data.get("ID");
//                String cron = (String) data.get("CRON");
//                uStmt.setString(1, cron);
//                uStmt.setString(2, id);
//                uStmt.executeUpdate();
//            }
        }
    }

    @Override
    public void close() throws Exception {
        super.close();

        if(pstmt != null) {
            pstmt.close();
        }

        if(connection != null) {
            connection.close();
        }
    }

}

git:

classtime2020/sqlServer2ClickHouse at master · zhaobingkun/classtime2020 · GitHub文章來源地址http://www.zghlxwxcb.cn/news/detail-404328.html

到了這里,關(guān)于用flink cdc sqlserver 將數(shù)據(jù)實時同步到clickhouse的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 基于Flink CDC實時同步數(shù)據(jù)(MySQL到MySQL)

    基于Flink CDC實時同步數(shù)據(jù)(MySQL到MySQL)

    jdk8 Flink 1.16.1(部署在遠(yuǎn)程服務(wù)器:192.168.137.99) Flink CDC 2.3.0 MySQL 8.0(安裝在本地:192.168.3.31) (安裝部署過程略) 準(zhǔn)備三個數(shù)據(jù)庫:flink_source、flink_sink、flink_sink_second。 將flink_source.source_test表實時同步到flink_sink和flink_sink_second的sink_test表。 (建庫建表過程略) 開發(fā)過程

    2024年02月06日
    瀏覽(27)
  • 【FLINK】Kafka數(shù)據(jù)源通過Flink-cdc進(jìn)行實時數(shù)據(jù)同步

    【FLINK】Kafka數(shù)據(jù)源通過Flink-cdc進(jìn)行實時數(shù)據(jù)同步

    CDC是Change Data Capture的縮寫,中文意思是 變更數(shù)據(jù)獲取 ,flink-cdc的作用是,通過flink捕獲數(shù)據(jù)源的事務(wù)變動操作記錄,包括數(shù)據(jù)的增刪改操作等,根據(jù)這些記錄可作用于對目標(biāo)端進(jìn)行實時數(shù)據(jù)同步。 下圖是flink-cdc最新支持的數(shù)據(jù)源類型: kafka的數(shù)據(jù)源要通過flink-cdc進(jìn)行實時數(shù)

    2024年02月12日
    瀏覽(36)
  • 基于 Flink CDC 構(gòu)建 MySQL 到 Databend 的 實時數(shù)據(jù)同步

    基于 Flink CDC 構(gòu)建 MySQL 到 Databend 的 實時數(shù)據(jù)同步

    這篇教程將展示如何基于 Flink CDC 快速構(gòu)建 MySQL 到 Databend 的實時數(shù)據(jù)同步。本教程的演示都將在 Flink SQL CLI 中進(jìn)行,只涉及 SQL,無需一行 Java/Scala 代碼,也無需安裝 IDE。 假設(shè)我們有電子商務(wù)業(yè)務(wù),商品的數(shù)據(jù)存儲在 MySQL ,我們需要實時把它同步到 Databend 中。 接下來的內(nèi)容

    2024年02月10日
    瀏覽(29)
  • 使用Flink CDC將Mysql中的數(shù)據(jù)實時同步到ES

    最近公司要搞搜索,需要把mysql中的數(shù)據(jù)同步到es中來進(jìn)行搜索,由于公司已經(jīng)搭建了flink集群,就打算用flink來做這個同步。本來以為很簡單,跟著官網(wǎng)文檔走就好了,結(jié)果沒想到折騰了將近一周的時間…… 我也是沒想到,這玩意網(wǎng)上資源竟然這么少,找到的全部都是通過

    2024年02月11日
    瀏覽(25)
  • 基于 Flink CDC 的實時同步系統(tǒng)

    基于 Flink CDC 的實時同步系統(tǒng)

    摘要: 本文整理自科杰科技大數(shù)據(jù)架構(gòu)師張軍,在 FFA 2022 數(shù)據(jù)集成專場的分享。本篇內(nèi)容主要分為四個部分: 功能概述 架構(gòu)設(shè)計 技術(shù)挑戰(zhàn) 生產(chǎn)實踐 Tips: 點(diǎn)擊 「閱讀原文」 查看原文視頻演講 ppt 科杰科技是專門做大數(shù)據(jù)服務(wù)的供應(yīng)商,目前的客戶包括能源、金融、證券等

    2024年02月05日
    瀏覽(31)
  • flink oracle cdc實時同步(超詳細(xì))

    flink oracle cdc實時同步(超詳細(xì))

    官方文檔:https://github.com/ververica/flink-cdc-connectors/blob/release-master/docs/content/connectors/oracle-cdc.md 本文參照官方文檔來記錄Oracle CDC 的配置。 在本文開始前,需要先安裝Oracle,有興趣的同學(xué)可以參考博主之前寫的《docker下安裝oracle11g(一次安裝成功)》。 如果要做oracle的實時同步

    2024年02月12日
    瀏覽(21)
  • flink postgresql cdc實時同步(含pg安裝配置等)

    類型 版本/描述 docker 20.10.9 Postgresql 10.6 初始化賬號密碼:postgres/postgres 普通用戶:test1/test123 數(shù)據(jù)庫:test_db flink 1.13.6 step1 : 拉取 PostgreSQL 10.6 版本的鏡像: step2 :創(chuàng)建并啟動 PostgreSQL 容器,在這里,我們將把容器的端口 5432 映射到主機(jī)的端口 30028,賬號密碼設(shè)置為 postgre

    2024年02月11日
    瀏覽(27)
  • Flink CDC 基于mysql binlog 實時同步mysql表

    Flink CDC 基于mysql binlog 實時同步mysql表

    環(huán)境說明: flink?1.15.2 mysql 版本5.7? ? 注意:需要開啟binlog,因為增量同步是基于binlog捕獲數(shù)據(jù) windows11 IDEA 本地運(yùn)行 先上官網(wǎng)使用說明和案例:MySQL CDC Connector — Flink CDC documentation 1. mysql開啟binlog (注意,引擎是 InnoDB,如果是ndbcluster,本人測試是捕獲不到binlog日志的,增量相

    2024年02月10日
    瀏覽(24)
  • Flink CDC2.4 整庫實時同步MySql 到Doris

    ????????Flink 1.15.4? ? ? ? ? 目前有很多工具都支持無代碼實現(xiàn)Mysql - Doris 的實時同步 ? ? ? ? 如:SlectDB 已發(fā)布的功能包 ? ? ? ? ? ? ? ??Dinky?SeaTunnel?TIS?等等 ? ? ? ? ?不過好多要么不支持表結(jié)構(gòu)變動,要不不支持多sink,我們的業(yè)務(wù)必須支持對表結(jié)構(gòu)的實時級變動

    2024年02月11日
    瀏覽(35)
  • Flink CDC 基于mysql binlog 實時同步mysql表(無主鍵)

    Flink CDC 基于mysql binlog 實時同步mysql表(無主鍵)

    環(huán)境說明: flink 1.15.2 mysql 版本5.7 ? ?注意:需要開啟binlog,因為增量同步是基于binlog捕獲數(shù)據(jù) windows11 IDEA 本地運(yùn)行 具體前提設(shè)置,請看這篇,包含 binlog 設(shè)置、Maven...... Flink CDC 基于mysql binlog 實時同步mysql表_彩虹豆的博客-CSDN博客 經(jīng)過不懈努力,終于從阿里help頁面找到了支

    2024年02月08日
    瀏覽(27)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包