flink--自定义sink

本文展示了如何在 Flink 中自定义 JDBC Sink,从文本文件读取数据,转换为 SensorReading 类型,然后将数据写入 MySQL 数据库,实现数据更新与插入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义sink

public class SinkToJDBC {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> inputStream =
                env.readTextFile("D:\\Tool\\Idea2020\\FlinkTest\\src\\main\\resources\\file.txt");
        //转换类型
        SingleOutputStreamOperator<SensorReading> dataStream = inputStream.map(new MapFunction<String, SensorReading>() {
            @Override
            public SensorReading map(String s) throws Exception {
                String[] splits = s.split(",");
                return new SensorReading(splits[0],new Long(splits[1]),new Double(splits[2]));
            }
        });

        dataStream.addSink(new MyJDBCSink());

        env.execute();

    }
    //自定义sinkfunction
    public static class MyJDBCSink extends RichSinkFunction<SensorReading> {

        Connection conn = null;
        PreparedStatement insertStmt =null;
        PreparedStatement updateStmt =null;
        @Override
        public void open(Configuration parameters) throws Exception {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/***?serverTimezone=Asia/Shanghai","root","****");
            insertStmt=conn.prepareStatement("insert into sensor_temp(id,temp) values(?,?)");
            updateStmt=conn.prepareStatement("update sensor_temp set temp= ? where id = ?");
        }

        @Override
        public void invoke(SensorReading value, Context context) throws Exception {
            //直接执行更新语句
            updateStmt.setDouble(1,value.getTemperature());
            updateStmt.setString(2,value.getId());
            updateStmt.execute();
            //if failed
            if(updateStmt.getUpdateCount() == 0){
                insertStmt.setDouble(2,value.getTemperature());
                insertStmt.setString(1,value.getId());
                insertStmt.execute();
            }
        }

        @Override
        public void close() throws Exception {
            insertStmt.close();
            updateStmt.close();
            conn.close();
        }
    }

answer:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值