MySQL Sink
在Flink流式数据处理中Sink常用的有Kafka,ES,MySQL,今天来看下,Flink中怎么使用JdbcSink将数据流写入MySQL中
配置
参考
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
);
执行代码后,数据库就会有数据了

本文介绍了如何在Flink流处理中使用JdbcSink将数据流写入MySQL数据库。首先,展示了所需的依赖配置,包括Flink JDBC connector和MySQL驱动。接着,通过创建一个简单的数据流并调用JdbcSink进行处理,详细说明了如何配置连接选项,如URL、驱动名、用户名和密码。最后,给出了创建MySQL数据库和表的SQL语句,以及执行代码后数据库中会存储的数据。
7906

被折叠的 条评论
为什么被折叠?



