1、工程代码如下
package com.atguigu.chapter0905;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import javax.sql.rowset.JdbcRowSet;
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?100", 3000L),
new Event("Bob", "./prod?id=1", 3300L),
new Event("Alice", "./prod?200", 3200L),
new Event("Bob", "./home", 3500L),
new Event("Bob", "./prod?id=2", 3800L),
new Event("Bob", "./prod?id=3", 4200L)
);
//jdbcSink并不是没有继承richsinkfunction或者对应的实现什么接口,而是在里边定义了一个静态的sink方法,
//他的返回结果是一个sinkfunction,所以就不是直接jdbcsink new他的一个对象,而是调用他的sink方法
stream.addSink(JdbcSink.sink(
"INSERT INTO clicks (user,url) VALUES (?, ?)",
((statement,event) -> {
statement.setString(1, event.user());
statement.setString(2, event.url());
}),
new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
.withUrl("jdbc:mysql://10.0.81.151:3306/flinkmusql")
.withDriverName("com.mysql.jdbc.Driver")
.withUsername("su")
.withPassword("1u%VOMW$er")
.build()
));
env.execute();
}
}
2、封装的Event类
package com.atguigu.chapter0905;
import java.sql.Timestamp;
/*
2022.8.30
*/
public class Event {
public String user;
public String url;
public Long timestamp;
public Event() {
}
public Event(String user, String url, Long timestamp) {
this.user = user;
this.url = url;
this.timestamp = timestamp;
}
@Override
public String toString() {
return "Event{" +
"user='" + user + '\'' +
", url='" + url + '\'' +
//把当前的长整型时间戳作为1970年7.1号0点开始的毫秒数来进行的转化
", timestamp=" + new Timestamp(timestamp) +
'}';
}
public String user() {
return user;
}
public String url() {
return url;
}
}
3、在mysql新建数据库flinkmysql
在数据库中新建表命名为clicks
create table clicks(
user varchar(20) not null,
url varchar(100) not null
);
show tables ;
select * from clicks;
4、执行flink代码
5、去mysql中查看写进去的数据
select * from clicks;