我想知道为什么我真的需要创建自己的RichSinkFunction或使用JDBCOutputFormat来在数据库上进行连接,而不仅仅是创建我的连接,执行查询并使用我的SinkFunction中的传统PostgreSQL驱动程序关闭连接?
我发现有很多文章告诉我这样做,但是没有解释为什么?有什么区别?
使用JDBCOutputFormat的代码示例
JDBCOutputFormat jdbcOutput = JDBCOutputFormat.buildJDBCOutputFormat()
.setDrivername("org.postgresql.Driver")
.setDBUrl("jdbc:postgresql://localhost:1234/test?user=xxx&password=xxx")
.setQuery(query)
.setSqlTypes(new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR }) //set the types
.finish();
实现自己的RichSinkFunction的代码示例,
public class RichCaseSink extends RichSinkFunction<Case> {
private static final String UPSERT_CASE = "INSERT INTO public.cases (caseid, tracehash) "
+ "VALUES (?, ?) "
+ "ON CONFLICT (caseid) DO UPDATE SET "
+ " tracehash=?";
private PreparedStatement statement;
@Override
public void invoke(Case aCase) throws Exception {
statement.setString(1, aCase.getId());
statement.setString(2, aCase.getTraceHash());
statement.setString(3, aCase.getTraceHash());
statement.addBatch();
statement.executeBatch();
}
@Override
public void open(Configuration parameters) throws Exception {
Class.forName("org.postgresql.Driver");
Connection connection =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/casedb?user=signavio&password=signavio");
statement = connection.prepareStatement(UPSERT_CASE);
}
}
为什么我不能只使用PostgreSQL驱动程序?
public class Storable implements SinkFunction<Activity>{
@Override
public void invoke(Activity activity) throws Exception {
Class.forName("org.postgresql.Driver");
try(Connection connection =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/casedb?user=signavio&password=signavio")){
statement = connection.prepareStatement(UPSERT_CASE);
//Perform the query
//close connection...
}
}
}
有人知道Flink最佳做法的技术答案吗? RichSinkFunction的实现或JDBCOutputFormat的使用是否有特殊之处?
谢谢。
答案 0 :(得分:2)
好吧,您可以使用自己的SinkFunction
,将仅使用invoke()
方法来打开连接并写入数据,它通常应该可以正常工作。但是在大多数情况下,它的性能会非常非常差。
第一个示例和第二个示例之间的实际区别是,在RichSinkFunction
中,您正在使用open()
方法打开连接并准备语句。该open()
方法在函数初始化时仅被调用一次。在第二个示例中,您将打开与数据库的连接并在invoke()
方法内准备prepare语句,该方法将为输入DataStream
的每个元素调用。实际上,您将为流中的每个元素。
创建数据库连接是一件昂贵的事情,并且肯定会带来严重的性能缺陷。