Flink写入MySQL

MySQL Sink

在Flink流式数据处理中Sink常用的有Kafka,ES,MySQL,今天来看下,Flink中怎么使用JdbcSink将数据流写入MySQL中

配置

参考

FLINK 基础配置

POM

	<!--mysql-->
	<dependency>
	  <groupId>org.apache.flink</groupId>
	  <artifactId>flink-connector-jdbc_${scala.binary.version}</artifactId>
	  <version>${flink.version}</version>
	</dependency>
	<dependency>
	  <groupId>mysql</groupId>
	  <artifactId>mysql-connector-java</artifactId>
	  <version>8.0.29</version>
	</dependency>

模拟一些数据,处理后写入MySQL

package org.example.flink.level2;

/**
 * sink mysql
 */

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class SinkToMySQL {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Event> stream = env.fromElements(
                new Event("Mary", "./home", 1000L),
                new Event("Bob", "./cart", 2000L),
                new Event("Alice", "./prod?id=100", 3000L),
                new Event("Alice", "./prod?id=200", 3500L),
                new Event("Bob", "./prod?id=2", 2500L),
                new Event("Alice", "./prod?id=300", 3600L),
                new Event("Bob", "./home", 3000L),
                new Event("Bob", "./prod?id=1", 2300L),
                new Event("Bob", "./prod?id=3", 3300L));

        stream.addSink(
                JdbcSink.sink(
                        "INSERT INTO clicks (user, url) VALUES (?, ?)",
                        (statement, r) -> {
                            statement.setString(1, r.user);
                            statement.setString(2, r.url);
                        },
                        new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                                .withUrl("jdbc:mysql://localhost:3306/flink")
                                .withDriverName("com.mysql.cj.jdbc.Driver")
                                .withUsername("root")
                                .withPassword("root")
                                .build()
                )
        );
        
        env.execute();
    }
}


创建库表SQL

create database if not exists flink;

use flink;

drop table if exists clicks;

create table if not exists clicks(
    user varchar(100) not null ,
    url varchar(100) not null
);

执行代码后,数据库就会有数据了

在这里插入图片描述

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Flink中将数据写入MySQL的步骤如下: 1. 引入MySQL驱动 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> ``` 2. 创建MySQL连接 在Flink中创建MySQL连接需要使用JDBC连接,可以通过以下代码创建MySQL连接: ```java Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); ``` 其中,"jdbc:mysql://localhost:3306/test"是连接MySQL数据库的URL,"root"和"password"分别是MySQL数据库的用户名和密码。 3. 实现MySQL输出格式化器 Flink中提供了多种输出格式化器,可以根据需要选择使用。对于MySQL,可以使用JDBCOutputFormat。具体实现如下: ```java public class MySQLOutputFormat implements OutputFormat<Tuple2<String, Integer>> { private PreparedStatement ps; private Connection connection; private String username; private String password; private String url; private String driverClassName; public MySQLOutputFormat(String username, String password, String url, String driverClassName) { this.username = username; this.password = password; this.url = url; this.driverClassName = driverClassName; } @Override public void configure(Configuration parameters) { } @Override public void open(int taskNumber, int numTasks) throws IOException { try { Class.forName(driverClassName); connection = DriverManager.getConnection(url, username, password); String sql = "INSERT INTO word_count (word, count) VALUES (?, ?)"; ps = connection.prepareStatement(sql); } catch (Exception e) { e.printStackTrace(); } } @Override public void writeRecord(Tuple2<String, Integer> record) throws IOException { try { ps.setString(1, record.f0); ps.setInt(2, record.f1); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } @Override public void close() throws IOException { try { if (ps != null) { ps.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } ``` 在上述代码中,我们实现了OutputFormat接口,并重写了configure、open、writeRecord和close方法。其中,configure和close方法不需要实现,因为我们没有需要配置的参数和资源需要释放。 在open方法中,我们通过JDBC连接获取MySQL连接,并创建PreparedStatement对象。在writeRecord方法中,我们将数据插入到MySQL中。在close方法中,我们释放了MySQL连接和PreparedStatement对象。 4. 调用MySQL输出格式化器 在Flink中调用MySQL输出格式化器的代码如下: ```java DataStream<Tuple2<String, Integer>> wordCounts = ... MySQLOutputFormat outputFormat = new MySQLOutputFormat("root", "password", "jdbc:mysql://localhost:3306/test", "com.mysql.jdbc.Driver"); wordCounts.writeUsingOutputFormat(outputFormat); ``` 在上述代码中,我们通过writeUsingOutputFormat方法将数据写入MySQL中。 总的来说,将数据写入MySQL的步骤就是:引入MySQL驱动、创建MySQL连接、实现MySQL输出格式化器、调用MySQL输出格式化器。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BirdMan98

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值