在flink中没有现成的用来写入MySQL的sink,但是flink提供了一个类,JDBCOutputFormat,通过这个类,如果你提供了jdbc的driver,则可以当做sink使用。
JDBCOutputFormat其实是flink的batch api,但也可以用来作为stream的api使用,社区也推荐通过这种方式来进行。
JDBCOutputFormat用起来很简单,只需要一个prepared statement,driver和database connection,就可以开始使用了。
... 参考:flink写入mysql的两种方式
但有一点要明确,JDBCOutputFormat只能处理Row,而Row是对prepared statement的参数的一个包装类。这意味着我们需要将流中的case转换为row,通过map就能做的。
JDBCOutputFormat
还有一个很有用的参数,batchInterval,见名知意,就是多少数据提交一次,尽量高效率的向数据库提交数据。当然还有比如timeout等其他参数,可以探索。
这里讲JDBCInputFormat+JDBCOutputFormat
1、pom.xml
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-jdbc_2.11</artifactId>
<version>1.9.1</version>
</dependency>
2、代码
ExecutionEnvironment env = ExecutionEnvironment.createRemoteEnvironment("localhost", 8081, "D:\\flink-steven\\target\\flink-0.0.1-SNAPSHOT.jar");
//读mysql
DataSource<Row> dataSource = env.createInput(JDBCInputFormat.buildJDBCInputFormat()
.setDrivername("com.mysql.jdbc.Driver")
.setDBUrl("jdbc:mysql://localhost:3306")
.setUsername("root")
.setPassword("root")
.setQuery("select id,dq from flink.ajxx_xs ")
.setRowTypeInfo(new RowTypeInfo(BasicTypeInfo.INT_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO))
.finish());
final BatchTableEnvironment tableEnv = BatchTableEnvironment.create(env);
tableEnv.registerDataSet("ods_tb01", dataSource);
Table query = tableEnv.sqlQuery("select * from ods_tb01");
DataSet<Row> result = tableEnv.toDataSet(query, Row.class);
result.print();
result.output(JDBCOutputFormat.buildJDBCOutputFormat()
.setDrivername("com.mysql.jdbc.Driver")
.setDBUrl("jdbc:mysql://localhost:3306")
.setUsername("root")
.setPassword("root")
.setQuery("insert into flink.ajxx_xs2 (id,dq) values (?,?)")
.setSqlTypes(new int[]{Types.INTEGER, Types.NCHAR})
.finish());
env.execute("flink-test");