Flink 程序Sink(数据输出)操作(3)自定义Mysql-Sink

Flink 程序Sink(数据输出)操作(3)自定义Mysql-Sink

自定义sink需要继承RichSinkFunction

ex:

public static class MysqlSink extends RichSinkFunction<IN> {}

必要依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

自定义Mysql-sink

public static class MysqlSink extends RichSinkFunction<VehicleAlarm> {
        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://xx:3306/alarm-sc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String username = "root";
        String password = "xx";

        /**
         * 首次sink时执行,且创建到销毁只会执行一次
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            // 获取mysql 连接
            conn = DriverManager.getConnection(url, username, password);
            // 关闭自定提交
            conn.setAutoCommit(false);
        }

        /**
         * 数据源无数据,sink关闭时执行,且创建到销毁只会执行一次
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            if (conn != null) {
                conn.close();
            }
            if (ps != null) {
                ps.close();
            }
        }

        /**
         * 数据输出时执行,每一个数据输出时,都会执行此方法
         * @param value
         * @param context
         * @throws Exception
         */
        @Override
        public void invoke(VehicleAlarm value, Context context) throws Exception {
            String sql = "insert into vehicle_alarm_202104 (`id`,`license_plate`,`plate_color`,`device_time`,`zone`) " +
                    "values(?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, value.id);
            ps.setString(2, value.licensePlate);
            ps.setString(3, value.plateColor);
            ps.setLong(4, value.deviceTime);
            ps.setString(5, value.zone);
            // 执行语句
            ps.execute();
            // 提交
            conn.commit();
            log.warn("sink-success:{}", value);
        }
    }

Flink程序步骤

public static void main(String[] args) throws Exception {
    //准备环境
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
    // 加载数据源
    DataStreamSource<VehicleAlarm> streamSource = env.addSource(new MySource());
    //todo  transformation(数据处理)

    // 数据输出 
    streamSource.addSink(new MysqlSink());
    // 程序执行
    env.execute("learn-mysql-sink");
}

image-20210411221421932

附上完整DEMO

package com.leilei;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
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 org.apache.flink.streaming.api.functions.source.SourceFunction;

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

/**
 * @author lei
 * @version 1.0
 * @date 2021/3/11 21:09
 * @desc flink 1.12中 sink操作 输出到Mysql数据库
 */
@Slf4j
public class FlinkSink3_Mysql {
    public static void main(String[] args) throws Exception {
        //准备环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
        // 加载数据源
        DataStreamSource<VehicleAlarm> streamSource = env.addSource(new MySource());
        //todo  transformation(数据处理)

        // 数据输出
        streamSource.addSink(new MysqlSink());
        // 程序执行
        env.execute("learn-mysql-sink");
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class VehicleAlarm {
        private String id;
        private String licensePlate;
        private String plateColor;
        private Long deviceTime;
        private String zone;
    }

    /**
     * 自定义数据源
     */
    public static class MySource implements SourceFunction<VehicleAlarm> {
        @Override
        public void run(SourceContext<VehicleAlarm> ctx) throws Exception {
            while (true) {
                long id = System.currentTimeMillis();
                VehicleAlarm vehicleAlarm = new VehicleAlarm(String.valueOf(id), "川A" + id,
                        "绿", System.currentTimeMillis(), "sc");
                ctx.collect(vehicleAlarm);
                Thread.sleep(10000);
            }
        }

        @Override
        public void cancel() {
        }
    }

    /**
     * 自定义mysql sink
     */
    public static class MysqlSink extends RichSinkFunction<VehicleAlarm> {
        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://xxx:3306/alarm-sc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String username = "root";
        String password = "xxx";

        /**
         * 首次sink时执行,且创建到销毁只会执行一次
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            conn = DriverManager.getConnection(url, username, password);
            conn.setAutoCommit(false);
        }

        /**
         * 数据源无数据,sink关闭时执行,且创建到销毁只会执行一次
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            if (conn != null) {
                conn.close();
            }
            if (ps != null) {
                ps.close();
            }
        }

        /**
         * 数据输出时执行,每一个数据输出时,都会执行此方法
         * @param value
         * @param context
         * @throws Exception
         */
        @Override
        public void invoke(VehicleAlarm value, Context context) throws Exception {
            String sql = "insert into vehicle_alarm_202104 (`id`,`license_plate`,`plate_color`,`device_time`,`zone`) " +
                    "values(?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, value.id);
            ps.setString(2, value.licensePlate);
            ps.setString(3, value.plateColor);
            ps.setLong(4, value.deviceTime);
            ps.setString(5, value.zone);
            ps.execute();
            conn.commit();
            log.warn("sink-success:{}", value);
        }
    }


}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
非常感谢您的提问!如果您想要在Flink中获取MySQL多张表的信息,可以按照如下步骤进行: 1. 首先需要在Flink中使用JDBC连接器连接MySQL数据库,并创建一个JDBC输入源,以便从MySQL中读取数据。 2. 然后可以通过Flink的Table API或SQL API将多张表的数据进行连接或者关联,从而得到您需要的数据。 3. 最后可以使用自定义Sink数据写入MySQL中。下面就是一个简单的Java代码示例,可以帮助您实现该功能: ``` public class FlinkMySQLSink { public static void main(String[] args) throws Exception { // set up the execution environment StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // set up JDBC connection options String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "password"; String driverName = "com.mysql.jdbc.Driver"; // create a JDBC input source to read multiple tables from MySQL JdbcInputFormat jdbcInputFormat = JdbcInputFormat.buildJdbcInputFormat() .setDrivername(driverName) .setDBUrl(url) .setUsername(username) .setPassword(password) .setQuery("SELECT * FROM table1; SELECT * FROM table2;") .finish(); // create a data stream from the JDBC input source DataStream<Tuple2<String, String>> inputDataStream = env.createInput(jdbcInputFormat); // use Table API or SQL API to join or combine multiple tables Table table = inputDataStream .map(new MapFunction<Tuple2<String, String>, Row>() { public Row map(Tuple2<String, String> value) throws Exception { return Row.of(value.f0, value.f1); } }) .toTable(new TableSchema(new String[]{"column1", "column2"}, new TypeInformation[]{Types.STRING, Types.STRING})); // create a custom Sink to write data back to MySQL JDBCOutputFormat jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat() .setDrivername(driverName) .setDBUrl(url) .setUsername(username) .setPassword(password) .setQuery("INSERT INTO result_table (column1, column2) VALUES (?, ?)") .finish(); // write the data stream to the custom Sink table.writeToSink(jdbcOutputFormat); // execute the Flink job env.execute("Flink MySQL Sink Example"); } } ``` 在这个示例中,我们首先设置了JDBC连接器所需的参数,然后使用JdbcInputFormat创建了一个JDBC输入源,该源可以从MySQL中读取多个表的数据。 接下来,我们使用Table API或SQL API将多个表的数据连接或者关联起来,并生成一个包含所需数据的Table对象。 最后,我们使用自定义的JDBCOutputFormat创建一个Sink,将Table中的数据写回到MySQL中。在这个Sink中,我们需要指定要写入哪个表,以及如何将数据映射到表中的列。 希望这个示例可以帮助您实现获取MySQL多张表信息的功能!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值