flink: 通过Sink将数据写入MySQL

文章介绍了使用ApacheFlink在Java中通过JDBC连接MySQL,以及将数据流发送到Elasticsearch、Kafka和Redis的示例,展示了如何创建和执行流处理任务。
摘要由CSDN通过智能技术生成

一、依赖添加

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

        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-jdbc_2.12</artifactId>
            <version>1.11.1</version>
        </dependency>

二、两种方式写MySQL:

package cn.edu.tju.demo;

import org.apache.flink.api.common.functions.*;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.streaming.api.collector.selector.OutputSelector;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoMapFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch7.ElasticsearchSink;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;
import org.apache.flink.util.Collector;
import org.apache.http.HttpHost;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;

import java.util.*;

public class Test16 {
    private static String MYSQL_SERVER = "139.198.0.216";
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment
                .getExecutionEnvironment();


        DataStream<String> mySource = environment.readTextFile("demo.txt");

        String sql = "insert into userinfo(username,passwd) values  " +
                "(?,?)";
        JdbcConnectionOptions jdbcBuild = new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                .withDriverName("com.mysql.jdbc.Driver")
                .withUrl("jdbc:mysql://xx.xx.xx.xx:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false")
                .withUsername("root")
                .withPassword("123456")
                .build();

        mySource.addSink(JdbcSink.sink(sql, (ps, str) -> {
            ps.setString(1, str);
            ps.setString(2, str);

        }, jdbcBuild));



        environment.execute("my job");

    }




}






package cn.edu.tju.demo;

import org.apache.flink.api.common.functions.*;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.streaming.api.collector.selector.OutputSelector;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoMapFunction;
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 org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch7.ElasticsearchSink;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;
import org.apache.flink.util.Collector;
import org.apache.http.HttpHost;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;

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

public class Test17 {
    private static String MYSQL_SERVER = "xx.xx.xx.xx";
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment
                .getExecutionEnvironment();


        DataStream<String> mySource = environment.readTextFile("demo.txt");



        mySource.addSink(new MyJdbcSinkFunction());
        environment.execute("mysql");

    }


    public static class MyJdbcSinkFunction extends RichSinkFunction<String>{
        private Connection connection = null;
        private PreparedStatement insert = null;
        private PreparedStatement update = null;

        @Override
        public void open(Configuration parameters) throws Exception {
            connection = DriverManager.getConnection("jdbc:mysql://xx.xx.xx.xx:3306/test" +
                    "?useUnicode=true&characterEncoding=utf-8&useSSL=false", "root", "123456");

            insert = connection.prepareStatement("insert into userinfo(username,passwd) values(?,?)");
            System.out.println("open mysql");
        }

        @Override
        public void close() throws Exception {
            connection.close();
        }

        @Override
        public void invoke(String value, Context context) throws Exception {

            insert.setString(1, value);
            insert.setString(2, value);
            insert.execute();
        }
    }


}






要将实时计算的当天 PV 写入 MySQL,可以使用 Flink 的 JDBC Connector 连接器,将结果输出到 MySQL 数据库中。 以下是一个示例代码: ``` DataStream<Tuple2<String, Integer>> pvStream = ...; // 获取实时计算的当天 PV 数据流 // 将结果写入 MySQL pvStream.addSink(JdbcSink.sink( "INSERT INTO pv_count(date, pv) VALUES (?, ?)", (ps, t) -> { ps.setDate(1, new java.sql.Date(System.currentTimeMillis())); ps.setInt(2, t.f1); }, new JdbcConnectionOptions.JdbcConnectionOptionsBuilder() .withUrl("jdbc:mysql://localhost:3306/db") .withDriverName("com.mysql.jdbc.Driver") .withUsername("user") .withPassword("password") .build() )); ``` 其中,`pvStream` 是一个包含了当天 PV 数量的数据流。`JdbcSink.sink` 方法将数据写入 MySQL 数据库中,第一个参数是 SQL 语句,第二个参数是将数据写入 PreparedStatement 中的逻辑,第三个参数是连接 MySQL 的配置信息。 在这个示例中,我们使用了一个 `pv_count` 表,用于存储每天的 PV 数量。表中包含两个字段:`date` 用于存储日期,`pv` 用于存储当天的 PV 数量。在 `JdbcSink.sink` 的第一个参数中,我们使用了一个占位符 `?` 来表示这两个字段。在第二个参数中,我们将当前时间作为日期写入了 PreparedStatement 中的第一个参数,将当天 PV 数量写入了第二个参数。在第三个参数中,我们指定了连接 MySQL 数据库的配置信息。 这样,当 Flink 实时计算出当天的 PV 数量后,就会自动将结果写入 MySQL 数据库中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值