大数据-玩转数据-Flink 自定义Sink(Mysql)

一、说明

如果Flink没有提供给我们可以直接使用的连接器,那我们如果想将数据存储到我们自己的存储设备中,mysql 的安装使用请参考
mysql-玩转数据-centos7下mysql的安装

创建表

sql 复制代码
CREATE TABLE `sensor` (
  `id` int(10)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

二、pom.xml 导入驱动

复制代码
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
</dependency>

三、编写程序

sql 复制代码
package com.lyh.flink06;

import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

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

public class SinkMysql {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        DataStreamSource<Integer> dataStreamSource = env.fromElements(1, 2, 3, 4, 5, 6);
        KeyedStream<Integer, Integer> keyedStream = dataStreamSource.keyBy(new KeySelector<Integer, Integer>() {
            @Override
            public Integer getKey(Integer value) throws Exception {
                return value.intValue();
            }
        });
        keyedStream.addSink(new MysqlSink());
        env.execute();

    }
    public static class  MysqlSink extends RichSinkFunction<Integer>{

        private Connection sunbo;

        @Override
        public void open(Configuration parameters) throws Exception {
            Class.forName("com.mysql.cj.jdbc.Driver");
            sunbo = DriverManager.getConnection("jdbc:mysql://192.168.220.100:3306/test?useSSL=false", "sunbo", "Mysql123456#");

        }

        @Override
        public void close() throws Exception {
            if (sunbo != null) {
                sunbo.close();
            }
        }

        @Override
        public void invoke(Integer value, Context context) throws Exception {
            String sql = "insert into sensor(id)values(?)";
            PreparedStatement ps = sunbo.prepareStatement(sql);
            ps.setInt(1,value.intValue());
            ps.execute();
            ps.close();

        }
    }
}

四、运行测试

相关推荐
程序员不迷路26 分钟前
Flink学习
大数据·flink
hzp66632 分钟前
阿里云的centos8 服务器安装MySQL 8.0
mysql·阿里云·centos8
Raisy_3 小时前
05 ODS层(Operation Data Store)
大数据·数据仓库·kafka·flume
郭二哈3 小时前
git的使用
大数据·网络·git·elasticsearch
码luffyliu4 小时前
MySQL:MVCC机制及其在Java秋招中的高频考点
java·数据库·mysql·事务·并发·mvcc
水涵幽树4 小时前
MySQL 时间筛选避坑指南:为什么格式化字符串比较会出错?
数据库·后端·sql·mysql·database
subuq7 小时前
Web3.0 时代的电商系统:区块链如何解决信任与溯源问题?
大数据·网络·学习
@蓝眼睛8 小时前
mac的m3芯片安装mysql
mysql·macos
冰块的旅行8 小时前
MySQL 的时区问题
mysql
Lx3528 小时前
Hadoop数据倾斜问题诊断与解决方案
大数据·hadoop