FLINK 1.12 支持upsertSql 不再去使用了JDBCUpsertSINK了,kafka也支持upsert了

Stella981
• 阅读 1377
package com.konka.dsp;


import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.jdbc.dialect.MySQLDialect;
import org.apache.flink.connector.jdbc.internal.options.JdbcOptions;
import org.apache.flink.connector.jdbc.table.JdbcUpsertTableSink;
import org.apache.flink.formats.json.JsonFormatFactory;
import org.apache.flink.formats.json.canal.CanalJsonFormatFactory;
import org.apache.flink.shaded.curator4.org.apache.curator.framework.schema.Schema;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.*;
import org.apache.flink.table.api.bridge.java.BatchTableEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.expressions.TimeIntervalUnit;
import org.apache.flink.table.types.DataType;
import org.apache.flink.types.Row;
import org.apache.flink.util.CloseableIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.time.Duration;
import java.util.concurrent.ExecutionException;

import static org.apache.flink.table.api.Expressions.*;


public class SalesOrderStream {

    private static Logger log = LoggerFactory.getLogger(SalesOrderStream.class.getName());
    public static Table report(Table transactions) {

        return transactions.select(
                $("customer_name"),
                $("created_date"),
                $("total_amount"))
                .groupBy($("customer_name"),$("created_date"))
                .select(
                        $("customer_name"),
                        $("total_amount").sum().as("total_amount"),
                        $("created_date")
                        );

    }

    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment
                .getExecutionEnvironment();
//        env.setParallelism(4);
//        env.getConfig().setRestartStrategy(RestartStrategies.noRestart());
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

     // set default parallelism to 4


//        tEnv.executeSql("CREATE TABLE sales_order_header_stream (\n" +
////                "   id  BIGINT not null,\n" +
//                "    customer_name STRING,\n"+
////                "    dsp_org_name STRING,\n"+
//                "    total_amount      DECIMAL(38,2),\n" +
////                "    total_discount      DECIMAL(16,2),\n" +
////                "    pay_amount      DECIMAL(16,2),\n" +
////                "    total_amount      DECIMAL(16,2),\n" +
//                "    created_date TIMESTAMP(3)\n" +
//                ") WITH (\n" +
//                " 'connector' = 'mysql-cdc',\n" +
//                " 'hostname' = '192.168.8.73',\n" +
//                " 'port' = '4000',\n"+
//                " 'username' = 'flink',\n"+
//                " 'password' = 'flink',\n"+
//                " 'database-name' = 'dspdev',\n"+
//                " 'table-name' = 'sales_order_header'\n"+
//                ")");
        //pay_type,over_sell
        tEnv.executeSql("CREATE TABLE sales_order_header_stream (\n" +
                        " `id` BIGINT,\n"+
                        " `total_amount` DECIMAL(16,2) ,\n"+
                        " `customer_name` STRING,\n"+
                        " `order_no` STRING,\n"+
                        " `doc_type` STRING,\n"+
                        " `sales_org` STRING,\n"+
                        " `distr_chan` STRING,\n"+
                        " `division` STRING,\n"+
                        " `sales_grp` STRING,\n"+
                        " `sales_off` STRING,\n"+
                        " `purch_no_c` STRING,\n"+
                        " `purch_date` STRING,\n"+
                        " `sold_to` STRING,\n"+
                        " `ship_to` STRING,\n"+
                        " `r3_sales_order` STRING,\n"+
                        " `created_by_employee_name` STRING,\n"+
                        " `created_by_dept_name` STRING,\n"+
                        " `created_by_dept_name` STRING,\n"+
                        " `is_enable` BIGINT,\n"+
                        " `is_delete` BIGINT,\n"+
                        " `sale_order_status` STRING,\n"+
                        " `created_by_parent_dept_name` STRING,\n"+
                        " `total_discount` DECIMAL(16,2),\n"+
                        " `customer_sapcode` STRING,\n"+
                        " `sold_to_name` STRING,\n"+
                        " `ship_to_name` STRING,\n"+
                        " `total_discount_amount` DECIMAL(16,2),\n"+
                        " `other_discount` DECIMAL(16,2),\n"+
                        " `other_amount` DECIMAL(16,2),\n"+
                        " `pay_amount` DECIMAL(16,2),\n"+
                        " `dsp_org_name` STRING,\n"+
                        " `delivery_address` STRING,\n"+
                        " `delivery_person` STRING,\n"+
                        " `delivery_phone` STRING,\n"+
                        " `pay_type` STRING,\n"+
                        " `over_sell` STRING,\n"+
                        " `created_date` TIMESTAMP(3),\n"+
                        " PRIMARY KEY (`id`) NOT ENFORCED "+
                ") WITH (\n" +
                "'connector' = 'kafka',\n"+
                "'topic' = 'canal-data',\n"+
                "'properties.bootstrap.servers' = '192.168.8.71:9092',\n"+
                "'properties.group.id' = 'test',\n"+
                "'format' = 'canal-json'\n"+
                ")");

//        tEnv.executeSql("CREATE TABLE total_day_report (\n" +
//                "    customer_name STRING,\n" +
////                "    total_amount    DECIMAL(16,2),\n" +
////                "    total_discount  DECIMAL(16,2),\n" +
////                "    pay_amount      DECIMAL(16,2),\n" +
//                "    total_amount    DECIMAL(16,2),\n" +
//                "    created_date STRING,\n" +
//                "    PRIMARY KEY (created_date) NOT ENFORCED" +
//                ") WITH (\n" +
//                "  'connector' = 'upsert-kafka',\n" +
//                "  'topic' = 'customer_amount',\n" +
//                "  'properties.bootstrap.servers' = '192.168.8.71:9092',\n"+
//                "  'key.format' = 'json',\n"+
//                "  'value.format' = 'json',\n"+
//                "  'value.fields-include' = 'ALL'\n"+
//                ")");



        tEnv.executeSql("CREATE TABLE upsertSink (\n" +
                "    customer_name STRING,\n" +
//                "    total_amount    DECIMAL(16,2),\n" +
//                "    total_discount  DECIMAL(16,2),\n" +
//                "    pay_amount      DECIMAL(16,2),\n" +
                "    total_amount    DECIMAL(16,2),\n" +
                "    created_date STRING,\n" +
                "    PRIMARY KEY (customer_name,created_date) NOT ENFORCED" +
                ") WITH (\n" +
                        "  'connector' = 'tidb',\n" +
                        "  'tidb.database.url' = 'jdbc:mysql://192.168.8.73:4000/dspdev',\n" +
                        "  'tidb.username' = 'flink',\n"+
                        "  'tidb.password' = 'flink',\n"+
                        "  'tidb.database.name' = 'dspdev',\n"+
                        "  'tidb.table.name' = 'spend_report'\n"+
//                "  'connector.type'='jdbc'," +
//                "  'connector.url'='jdbc:mysql://192.168.8.73:4000/dspdev',\n" +
//                "  'connector.username' = 'flink',\n"+
//                "  'connector.password' = 'flink',\n"+
//                "  'connector.table' = 'spend_report'" +
                ")");
//        TableSchema tableSche = TableSchema.builder()
//                .field("customer_name",DataTypes.STRING().notNull())
//                .field("total_amount",DataTypes.DECIMAL(16,2))
//                .field("created_date",DataTypes.STRING().notNull()).build();
//
//        JdbcOptions jdbcOptions = JdbcOptions.builder()
//                .setDBUrl("jdbc:mysql://192.168.8.73:4000/dspdev")
//                .setTableName("spend_report")
//                .setUsername("flink")
//                .setPassword("flink")
//                .setDialect(new MySQLDialect())
//                .setDriverName("com.mysql.jdbc.Driver")
//                .build();
//        JdbcUpsertTableSink jdbcUpsertTableSink = JdbcUpsertTableSink.builder()
//                .setTableSchema(tableSche)
//                .setOptions(jdbcOptions)
//                .build();
//        jdbcUpsertTableSink.setKeyFields(new String[]{"id"});
        /**
         * SINK End
         */
//        tEnv.re("spend_report",jdbcUpsertTableSink);
        Table transactions = tEnv.from("sales_order_header_stream");
//      tEnv.executeSql("delete from total_day_report");
       tEnv.executeSql("insert into upsertSink select dsp_org_name as customer_name,cast(sum(t.pay_amount) as decimal(16,2)) as amount,DATE_FORMAT(t.created_date,'yyyy-MM-dd') as created_date from sales_order_header_stream t group by DATE_FORMAT(t.created_date,'yyyy-MM-dd'),dsp_org_name").print();
//      tEnv.executeSql("insert into spend_report select * from total_day_report");
//      Table transactions = tEnv.from("total_day_report");
//      report(transactions).executeInsert("spend_report");
        tEnv.execute("-----------");
    }


}

最后数据库结果如下: FLINK 1.12 支持upsertSql 不再去使用了JDBCUpsertSINK了,kafka也支持upsert了 每次都是更新替换,这样的话省去很多麻烦,不用转datastream在处理了,而且1.12支持upsert-kafka,最后数据叠加如下: FLINK 1.12 支持upsertSql 不再去使用了JDBCUpsertSINK了,kafka也支持upsert了 upsert-kafka上面已经体现,flink越来越强大了支持!~~~

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
3年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
3个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
9个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这