Flink之JDBCSink连接MySQL

输出到MySQL

  1. 添加依赖
xml 复制代码
<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-connector-jdbc</artifactId>
  <version>3.1.0-1.17</version>
</dependency>
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.32</version>
</dependency>
  1. 启动MySQL, 在test库下建表clicks
sql 复制代码
CREATE TABLE `clicks` (
  `user` VARCHAR(100) NOT NULL,
  `url` VARCHAR(100) DEFAULT NULL,
  `ts` BIGINT DEFAULT NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8
  1. 示例代码
java 复制代码
public class Flink04_JdbcSink {
    public static void main(String[] args) {
        //1.创建运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //默认是最大并行度
        env.setParallelism(1);

        DataStreamSource<Event> ds = Flink06_EventSource.getEventSource(env);

        //
        SinkFunction<Event> sink = JdbcSink.sink(
                "insert into clicks(user, url, ts) values (?,?,?)"
                , new JdbcStatementBuilder<Event>() {
                    @Override
                    public void accept(PreparedStatement preparedStatement, Event event) throws SQLException {
                        //给SQL的占位符赋值
                        preparedStatement.setString(1, event.getUser());
                        preparedStatement.setString(2, event.getUrl());
                        preparedStatement.setLong(3, event.getTs());
                    }
                },
                JdbcExecutionOptions.builder()
                        .withBatchSize(5)
                        .withBatchIntervalMs(10000)
                        .withMaxRetries(3)
                        .build()
                ,
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withDriverName("com.mysql.cj.jdbc.Driver")
                        .withUsername("root")
                        .withPassword("000000")
                        .withUrl("jdbc:mysql://hadoop102:3306/flink")
                        .build()
        );

        ds.addSink(sink);

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

MySQL的幂等性处理

  1. 将插入关键字替换为replace,如果主键重复,将除了主键外的所有字段都替换。
  2. 使用on duplicate key update 字段名 = values(字段名)语法,如果主键重复,可以选择部分字段进行替换,其余字段保持不变。
  3. 示例代码
java 复制代码
public class Flink05_JdbcSinkReplace {
    public static void main(String[] args) {
        //1.创建运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //默认是最大并行度
        env.setParallelism(1);

        DataStreamSource<Event> ds = Flink06_EventSource.getEventSource(env);

        SingleOutputStreamOperator<WordCount> countDs =
                ds.map(event -> new WordCount(event.getUrl(), 1))
                .keyBy(WordCount::getWord)
                .sum("count");

        //
        SinkFunction<WordCount> sink = JdbcSink.sink(
//                "replace into url_count(url, cnt) values (?,?)"
                "insert into url_count(url, cnt) values(?,?) on duplicate key update cnt = values(cnt)"
                ,
                new JdbcStatementBuilder<WordCount>() {
                    @Override
                    public void accept(PreparedStatement preparedStatement, WordCount wordCount) throws SQLException {
                        //注意:这里的起始下标是1
                        preparedStatement.setString(1, wordCount.getWord());
                        preparedStatement.setInt(2, wordCount.getCount());
                    }
                }
                ,
                JdbcExecutionOptions.builder()
                        .withBatchSize(5)
                        .withBatchIntervalMs(10000)
                        .withMaxRetries(3)
                        .build()
                ,
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withDriverName("com.mysql.cj.jdbc.Driver")
                        .withUsername("root")
                        .withPassword("000000")
                        .withUrl("jdbc:mysql://hadoop102:3306/flink")
                        .build()
        );

        countDs.addSink(sink);

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
相关推荐
Ytadpole7 小时前
MySQL 数据库优化设计:优化原理和数据库表设计技巧
数据库·mysql·优化·索引·查询·检索·表设计
言之。7 小时前
大模型嵌入 vs ES:语义搜索与关键字搜索
大数据·elasticsearch·搜索引擎
SirLancelot18 小时前
StarRocks-基本介绍(一)基本概念、特点、适用场景
大数据·数据库·数据仓库·sql·数据分析·database·数据库架构
Boop_wu8 小时前
[MySQL] 基础操作
数据库·mysql
阑梦清川8 小时前
es的docker部署和docker相关的可可视化面板工具介绍
大数据·elasticsearch·docker
Mr_LiYYD10 小时前
elasticsearch数据迁移
大数据·elasticsearch·搜索引擎
小糖学代码10 小时前
MySQL:14.mysql connect
android·数据库·mysql·adb
dalianwawatou10 小时前
GitLab 代码基础操作清单
大数据·elasticsearch·gitlab
Costrict10 小时前
解锁新阵地!CoStrict 现已支持 JetBrains 系列 IDE
大数据·ide·人工智能·深度学习·自然语言处理·ai编程·visual studio
wudl556611 小时前
Flink SQL 窗口函数详细
sql·flink·linq