rkhachatryan commented on a change in pull request #11061: [FLINK-15782] [connectors/jdbc] JDBC sink DataStream API URL: https://github.com/apache/flink/pull/11061#discussion_r385141186
########## File path: flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/JdbcBatchingOutputFormat.java ########## @@ -0,0 +1,298 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.api.java.io.jdbc; + +import org.apache.flink.api.common.functions.RuntimeContext; +import org.apache.flink.api.java.io.jdbc.executor.JdbcBatchStatementExecutor; +import org.apache.flink.api.java.tuple.Tuple2; +import org.apache.flink.runtime.util.ExecutorThreadFactory; +import org.apache.flink.types.Row; +import org.apache.flink.util.Preconditions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.Serializable; +import java.sql.SQLException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + +import static org.apache.flink.util.Preconditions.checkNotNull; + +class JdbcBatchingOutputFormat<In, JdbcIn, JdbcExec extends JdbcBatchStatementExecutor<JdbcIn>> extends AbstractJdbcOutputFormat<In> { + interface RecordExtractor<F, T> extends Function<F, T>, Serializable { + static <T> RecordExtractor<T, T> identity() { + return x -> x; + } + } + + interface ExecutorCreator<T extends JdbcBatchStatementExecutor<?>> extends Function<RuntimeContext, T>, Serializable { + } + + private static final long serialVersionUID = 1L; + + private static final Logger LOG = LoggerFactory.getLogger(JdbcBatchingOutputFormat.class); + + private final JdbcExecutionOptions executionOptions; + private final ExecutorCreator<JdbcExec> statementRunnerCreator; + final RecordExtractor<In, JdbcIn> jdbcRecordExtractor; + + private transient JdbcExec jdbcStatementExecutor; + private transient int batchCount = 0; + private transient volatile boolean closed = false; + + private transient ScheduledExecutorService scheduler; + private transient ScheduledFuture<?> scheduledFuture; + private transient volatile Exception flushException; + + JdbcBatchingOutputFormat( + JdbcConnectionProvider connectionProvider, + JdbcExecutionOptions executionOptions, + ExecutorCreator<JdbcExec> statementExecutorCreator, + RecordExtractor<In, JdbcIn> recordExtractor) { + super(connectionProvider); + this.executionOptions = executionOptions; + this.statementRunnerCreator = statementExecutorCreator; + this.jdbcRecordExtractor = recordExtractor; + } + + /** + * Connects to the target database and initializes the prepared statement. + * + * @param taskNumber The number of the parallel instance. + */ + @Override + public void open(int taskNumber, int numTasks) throws IOException { + super.open(taskNumber, numTasks); + jdbcStatementExecutor = statementRunnerCreator.apply(getRuntimeContext()); + try { + jdbcStatementExecutor.open(connection); + } catch (SQLException e) { + throw new IOException("unable to open JDBC writer", e); + } + if (executionOptions.getBatchIntervalMs() != 0 && executionOptions.getBatchSize() != 1) { + this.scheduler = Executors.newScheduledThreadPool(1, new ExecutorThreadFactory("jdbc-upsert-output-format")); + this.scheduledFuture = this.scheduler.scheduleWithFixedDelay(() -> { + synchronized (JdbcBatchingOutputFormat.this) { + if (!closed) { + try { + flush(); + } catch (Exception e) { + flushException = e; + } + } + } + }, executionOptions.getBatchIntervalMs(), executionOptions.getBatchIntervalMs(), TimeUnit.MILLISECONDS); + } + } + + private void checkFlushException() { + if (flushException != null) { + throw new RuntimeException("Writing records to JDBC failed.", flushException); + } + } + + @Override + public final synchronized void writeRecord(In record) { + checkFlushException(); + + try { + doWriteRecord(record); + batchCount++; + if (batchCount >= executionOptions.getBatchSize()) { + flush(); + } + } catch (Exception e) { + throw new RuntimeException("Writing records to JDBC failed.", e); + } + } + + void doWriteRecord(In record) throws SQLException { + jdbcStatementExecutor.process(jdbcRecordExtractor.apply(record)); + } + + @Override + public synchronized void flush() throws IOException { + checkFlushException(); + + for (int i = 1; i <= executionOptions.getMaxRetries(); i++) { + try { + attemptFlush(); Review comment: Yes. I would also replace `Thread.sleep(1000 * i);` with just rescheduling (retaining blocking semantics of `write`). But I'm not sure if such changes should be in this PR. WDYT? ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org With regards, Apache Git Services