├── .gitignore ├── picture ├── hongshen.png └── chenglong.png ├── src └── main │ └── java │ └── tech │ └── hongshen │ └── clickhouse │ ├── exception │ └── ClickhouseException.java │ ├── common │ ├── ClickhouseConstants.java │ ├── ChThreadFactory.java │ ├── ClickHouseConfig.java │ └── ConnectConfig.java │ ├── core │ ├── TableRowsBuffer.java │ ├── clickhouseRowCollector.java │ └── BatchProcessor.java │ └── ClickhouseSink.java ├── pom.xml ├── README.md ├── clickhouse-sink.iml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | /target/ 3 | /clickhouse-sinker.iml 4 | -------------------------------------------------------------------------------- /picture/hongshen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongbin86/flink-clickhouse-sink/HEAD/picture/hongshen.png -------------------------------------------------------------------------------- /picture/chenglong.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dongbin86/flink-clickhouse-sink/HEAD/picture/chenglong.png -------------------------------------------------------------------------------- /src/main/java/tech/hongshen/clickhouse/exception/ClickhouseException.java: -------------------------------------------------------------------------------- 1 | package tech.hongshen.clickhouse.exception; 2 | 3 | /** 4 | * @author hongshen 5 | * @date 2020/12/24 6 | */ 7 | public class ClickhouseException extends Exception { 8 | 9 | public ClickhouseException(String message) { 10 | super(message); 11 | } 12 | 13 | public ClickhouseException(String message, Throwable cause) { 14 | super(message, cause); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/tech/hongshen/clickhouse/common/ClickhouseConstants.java: -------------------------------------------------------------------------------- 1 | package tech.hongshen.clickhouse.common; 2 | 3 | /** 4 | * @author hongshen 5 | * @date 2020/12/24 6 | */ 7 | 8 | public class ClickhouseConstants { 9 | // clickhouse table name 10 | public static final String TARGET_TABLE_NAME = "table-name"; 11 | // how many rows in one request at most 12 | public static final String BATCH_SIZE = "batch-size"; 13 | //instances example: ip1:8123,ip2:8123 14 | public static final String INSTANCES = "clickhouse-instances"; 15 | public static final String USERNAME = "clickhouse-user"; 16 | public static final String PASSWORD = "clickhouse-password"; 17 | //flush interval in seconds 18 | public static final String FLUSH_INTERVAL = "flush-interval-sec"; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/tech/hongshen/clickhouse/core/TableRowsBuffer.java: -------------------------------------------------------------------------------- 1 | package tech.hongshen.clickhouse.core; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author hongshen 8 | * @date 2020/12/24 9 | */ 10 | public class TableRowsBuffer { 11 | 12 | private final String table; 13 | private final List rows; 14 | 15 | public TableRowsBuffer(String table) { 16 | this.table = table; 17 | this.rows = new ArrayList<>(); 18 | } 19 | 20 | public void add(String row) { 21 | rows.add(row); 22 | } 23 | 24 | public int bufferSize() { 25 | return rows.size(); 26 | } 27 | 28 | public List getRows() { 29 | return rows; 30 | } 31 | 32 | public String getTable() { 33 | return table; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/tech/hongshen/clickhouse/common/ChThreadFactory.java: -------------------------------------------------------------------------------- 1 | package tech.hongshen.clickhouse.common; 2 | 3 | import java.util.concurrent.ThreadFactory; 4 | 5 | /** 6 | * @author hongshen 7 | * @date 2020/12/24 8 | */ 9 | public class ChThreadFactory implements ThreadFactory { 10 | 11 | final ThreadGroup group; 12 | final String namePrefix; 13 | final int index; 14 | 15 | public ChThreadFactory(String namePrefix, int index) { 16 | this.namePrefix = namePrefix; 17 | this.index = index; 18 | SecurityManager s = System.getSecurityManager(); 19 | this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); 20 | } 21 | 22 | public Thread newThread(Runnable r) { 23 | Thread t = new Thread(this.group, r, this.namePrefix + "[T#" + index + "]", 0L); 24 | t.setDaemon(true); 25 | return t; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/tech/hongshen/clickhouse/core/clickhouseRowCollector.java: -------------------------------------------------------------------------------- 1 | package tech.hongshen.clickhouse.core; 2 | 3 | import java.util.concurrent.atomic.AtomicLong; 4 | 5 | import static org.apache.flink.util.Preconditions.checkNotNull; 6 | 7 | /** 8 | * @author hongshen 9 | * @date 2020/12/24 10 | */ 11 | public class clickhouseRowCollector { 12 | 13 | private final BatchProcessor batchProcessor; 14 | private final boolean flushOnCheckpoint; 15 | private final AtomicLong numPendingRowsRef; 16 | 17 | public clickhouseRowCollector(BatchProcessor batchProcessor, boolean flushOnCheckpoint, AtomicLong numPendingRowsRef) { 18 | this.batchProcessor = checkNotNull(batchProcessor); 19 | this.flushOnCheckpoint = flushOnCheckpoint; 20 | this.numPendingRowsRef = checkNotNull(numPendingRowsRef); 21 | } 22 | 23 | public void collect(String... rows) { 24 | for (String row : rows) { 25 | if (flushOnCheckpoint) { 26 | numPendingRowsRef.getAndIncrement(); 27 | } 28 | this.batchProcessor.add(row); 29 | } 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/tech/hongshen/clickhouse/common/ClickHouseConfig.java: -------------------------------------------------------------------------------- 1 | package tech.hongshen.clickhouse.common; 2 | 3 | import com.google.common.base.Preconditions; 4 | 5 | import java.io.Serializable; 6 | import java.util.Properties; 7 | 8 | /** 9 | * 10 | * @author hongshen 11 | * @date 2020/12/24 12 | * 13 | * */ 14 | 15 | import static tech.hongshen.clickhouse.common.ClickhouseConstants.FLUSH_INTERVAL; 16 | 17 | public class ClickHouseConfig implements Serializable { 18 | 19 | private static final long serialVersionUID = -2932592417524793016L; 20 | private final ConnectConfig connectConfig; 21 | 22 | private final int flushInterval; 23 | 24 | public ClickHouseConfig(Properties params) { 25 | this.connectConfig = new ConnectConfig(params); 26 | this.flushInterval = Integer.parseInt(params.getProperty(FLUSH_INTERVAL, "2")); 27 | Preconditions.checkArgument(flushInterval > 0); 28 | } 29 | 30 | public ConnectConfig getConnectConfig() { 31 | return connectConfig; 32 | } 33 | 34 | public int getFlushInterval() { 35 | return flushInterval; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/tech/hongshen/clickhouse/common/ConnectConfig.java: -------------------------------------------------------------------------------- 1 | package tech.hongshen.clickhouse.common; 2 | 3 | import com.google.common.base.Preconditions; 4 | 5 | import java.io.Serializable; 6 | import java.util.Arrays; 7 | import java.util.Base64; 8 | import java.util.List; 9 | import java.util.Properties; 10 | import java.util.concurrent.ThreadLocalRandom; 11 | import java.util.stream.Collectors; 12 | 13 | import static tech.hongshen.clickhouse.common.ClickhouseConstants.*; 14 | 15 | /** 16 | * @author hongshen 17 | * @date 2020/12/24 18 | */ 19 | public class ConnectConfig implements Serializable { 20 | 21 | private static final long serialVersionUID = 8769893930165013897L; 22 | public static final String HOST_DELIMITER = ", "; 23 | 24 | private final List hostsAndPorts; 25 | private final String userName; 26 | private final String password; 27 | private final String credentials; 28 | 29 | private int currentHostId = 0; 30 | 31 | public ConnectConfig(Properties parameters) { 32 | Preconditions.checkNotNull(parameters); 33 | String hostsString = parameters.getProperty(INSTANCES); 34 | Preconditions.checkNotNull(hostsString); 35 | hostsAndPorts = buildHostsAndPort(hostsString); 36 | Preconditions.checkArgument(hostsAndPorts.size() > 0); 37 | userName = parameters.getProperty(USERNAME, "default"); 38 | password = parameters.getProperty(PASSWORD, ""); 39 | credentials = buildCredentials(userName, password); 40 | } 41 | 42 | private static List buildHostsAndPort(String hostsString) { 43 | return Arrays.stream(hostsString 44 | .split(HOST_DELIMITER)) 45 | .map(ConnectConfig::checkHttpAndAdd) 46 | .collect(Collectors.toList()); 47 | } 48 | 49 | private static String checkHttpAndAdd(String host) { 50 | String newHost = host.replace(" ", ""); 51 | if (!newHost.contains("http")) { 52 | return "http://" + newHost; 53 | } 54 | return newHost; 55 | } 56 | 57 | private static String buildCredentials(String user, String password) { 58 | Base64.Encoder x = Base64.getEncoder(); 59 | String credentials = String.join(":", user, password); 60 | return new String(x.encode(credentials.getBytes())); 61 | } 62 | 63 | public String getRandomHostUrl() { 64 | currentHostId = ThreadLocalRandom.current().nextInt(hostsAndPorts.size()); 65 | return hostsAndPorts.get(currentHostId); 66 | } 67 | 68 | public String getCredentials() { 69 | return credentials; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | hongshen 8 | clickhouse-sink 9 | 1.0 10 | jar 11 | 12 | 13 | 14 | UTF-8 15 | 1.8 16 | 2.11 17 | 1.8.0 18 | 2.12.1 19 | 1.2.3 20 | 23.0 21 | 1.3.3 22 | 0.1.40 23 | 3.8.0 24 | 25 | 26 | 27 | 28 | 29 | 30 | com.typesafe 31 | config 32 | ${typesafe.config.version} 33 | 34 | 35 | 36 | com.google.guava 37 | guava 38 | ${guava.version} 39 | 40 | 41 | 42 | ch.qos.logback 43 | logback-classic 44 | ${logback.version} 45 | 46 | 47 | 48 | org.asynchttpclient 49 | async-http-client 50 | ${async.client.version} 51 | 52 | 53 | 54 | org.apache.flink 55 | flink-streaming-java_${scala.version} 56 | ${flink.version} 57 | 58 | 59 | 60 | 61 | 62 | 63 | org.apache.maven.plugins 64 | maven-compiler-plugin 65 | ${mvn.compiler.version} 66 | 67 | ${java.version} 68 | ${java.version} 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Flink clickhouse sink 2 | 3 | * simple and efficient, at least once guarantee 4 | * flink 1.8 is currently supported, and future versions are available for reference 5 | * instead of using JDBC, use clickHouse's HTTP interface directly 6 | 7 | ### why I create this tool 8 | 9 | At the beginning, I used this tool (https://github.com/ivi-ru/flink-clickhouse-sink), which linked to the official website, 10 | but I found that it would cause data loss, and the flink slot could not be released normally when the clickHouse server showed abnormal response, 11 | and the latest version also showed 'Out of memory', so I rewrote this tool for people who want a simple clickhouse sink. 12 | 13 | it has been well tested by chenglong.gu@perfma.com, have fun ! 14 | 15 | ## Sponsorship 16 | 17 | ![hongshen](https://github.com/dongbin86/flink-clickhouse-sink/blob/main/picture/hongshen.png) 18 | ![chenglong](https://github.com/dongbin86/flink-clickhouse-sink/blob/main/picture/chenglong.png) 19 | 20 | 21 | Thank you for your sponsorship and support 22 | 23 | 24 | ## Build 25 | 26 | `mvn clean package` 27 | 28 | 29 | ## Usage 30 | 31 | ``` 32 | import java.text.SimpleDateFormat 33 | import java.util.{Date, Properties} 34 | 35 | import com.alibaba.fastjson.JSON 36 | import tech.hongshen.clickhouse.ClickhouseSink 37 | import org.apache.flink.api.common.serialization.SimpleStringSchema 38 | import org.apache.flink.api.java.utils.ParameterTool 39 | import org.apache.flink.streaming.api.scala._ 40 | import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011 41 | 42 | /** 43 | * @author hongshen 44 | * @since 2020/12/24 45 | */ 46 | object SaveToClickhouseJob { 47 | 48 | def main(args: Array[String]): Unit = { 49 | val parameterTool = ParameterTool.fromArgs(args) 50 | val topic = parameterTool.get("kafka.topic.name", "hongshen") 51 | val env = StreamExecutionEnvironment.createLocalEnvironment() 52 | 53 | val ckSinkerProps = new Properties 54 | ckSinkerProps.put(ClickhouseConstants.TARGET_TABLE_NAME, "db.table") 55 | ckSinkerProps.put(ClickhouseConstants.BATCH_SIZE, "20000") 56 | 57 | ckSinkerProps.put(ClickhouseConstants.INSTANCES, "localhost:8123") 58 | ckSinkerProps.put(ClickhouseConstants.USERNAME, "default") 59 | ckSinkerProps.put(ClickhouseConstants.PASSWORD, "") 60 | ckSinkerProps.put(ClickhouseConstants.FLUSH_INTERVAL, "2") 61 | 62 | val kafkaProps = new Properties() 63 | kafkaProps.setProperty("bootstrap.servers", "localhost:9092") 64 | kafkaProps.setProperty("group.id", "hongshen") 65 | 66 | val myConsumer = new FlinkKafkaConsumer011[String](topic, new SimpleStringSchema(), kafkaProps) 67 | 68 | myConsumer.setStartFromEarliest() 69 | 70 | val sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") 71 | 72 | val records = env.addSource(myConsumer).map(s => { 73 | val data = JSON.parseObject(s, classOf[Data]) 74 | s"('${data.name}','${data.city}','${sdf.format(new Date(data.dateT))}','${data.ts}','${data.num}')" 75 | }) 76 | 77 | records.addSink(new ClickhouseSink(ckSinkerProps)).setParallelism(2) 78 | 79 | env.execute("kafka2clickhouse") 80 | } 81 | } 82 | ``` 83 | ## Notice 84 | 85 | The data format uses CSV format include '()' token on both side, and an INSERT statement is generated as follows 86 | 87 | `String.format("INSERT INTO %s VALUES %s", tableName, csv)` 88 | 89 | so you need convert your datastream event to that fomat, see the example above. 90 | 91 | ## Contributors 92 | 93 | * hongshen(dong_bin86@163.com) 94 | * chenglong(chenglong.gu@perfma.com) 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /src/main/java/tech/hongshen/clickhouse/ClickhouseSink.java: -------------------------------------------------------------------------------- 1 | package tech.hongshen.clickhouse; 2 | 3 | import org.apache.flink.configuration.Configuration; 4 | import org.apache.flink.runtime.state.FunctionInitializationContext; 5 | import org.apache.flink.runtime.state.FunctionSnapshotContext; 6 | import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction; 7 | import org.apache.flink.streaming.api.functions.sink.RichSinkFunction; 8 | import org.asynchttpclient.AsyncHttpClient; 9 | import org.asynchttpclient.Dsl; 10 | import org.asynchttpclient.Response; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import tech.hongshen.clickhouse.common.ClickHouseConfig; 14 | import tech.hongshen.clickhouse.core.BatchProcessor; 15 | import tech.hongshen.clickhouse.core.clickhouseRowCollector; 16 | import tech.hongshen.clickhouse.core.TableRowsBuffer; 17 | import tech.hongshen.clickhouse.exception.ClickhouseException; 18 | 19 | import java.util.Properties; 20 | import java.util.concurrent.atomic.AtomicLong; 21 | import java.util.concurrent.atomic.AtomicReference; 22 | 23 | import static tech.hongshen.clickhouse.common.ClickhouseConstants.BATCH_SIZE; 24 | import static tech.hongshen.clickhouse.common.ClickhouseConstants.TARGET_TABLE_NAME; 25 | 26 | /** 27 | * @author hongshen 28 | * @date 2020/12/24 29 | */ 30 | public class ClickhouseSink extends RichSinkFunction implements CheckpointedFunction { 31 | 32 | private static final long serialVersionUID = 8882341085011937977L; 33 | 34 | private static final Logger logger = LoggerFactory.getLogger(ClickhouseSink.class); 35 | 36 | private final Properties props; 37 | 38 | private final ClickHouseConfig config; 39 | 40 | 41 | private AtomicLong numPendingRows = new AtomicLong(0); 42 | private final AtomicReference failureThrowable = new AtomicReference<>(); 43 | 44 | private transient AsyncHttpClient client; 45 | private transient BatchProcessor batchProcessor; 46 | private transient clickhouseRowCollector clickhouseRowCollector; 47 | private boolean flushOnCheckpoint = true; 48 | 49 | public ClickhouseSink(Properties props) { 50 | this.props = props; 51 | this.config = new ClickHouseConfig(props); 52 | } 53 | 54 | @Override 55 | public void open(Configuration parameters) throws Exception { 56 | client = Dsl.asyncHttpClient(); 57 | batchProcessor = new BatchProcessor( 58 | client, 59 | config, 60 | getRuntimeContext().getIndexOfThisSubtask(), 61 | props.getProperty(TARGET_TABLE_NAME, ""), 62 | Integer.parseInt(props.getProperty(BATCH_SIZE, "10000")), 63 | new BatchProcessorListener() 64 | ); 65 | clickhouseRowCollector = new clickhouseRowCollector(batchProcessor, flushOnCheckpoint, numPendingRows); 66 | } 67 | 68 | @Override 69 | public void invoke(String value, Context context) throws Exception { 70 | checkErrorAndRethrow(); 71 | clickhouseRowCollector.collect(value); 72 | } 73 | 74 | @Override 75 | public void snapshotState(FunctionSnapshotContext functionSnapshotContext) throws Exception { 76 | checkErrorAndRethrow(); 77 | if (flushOnCheckpoint) { 78 | while (numPendingRows.get() != 0) { 79 | batchProcessor.flush(); 80 | checkErrorAndRethrow(); 81 | } 82 | } 83 | } 84 | 85 | @Override 86 | public void initializeState(FunctionInitializationContext functionInitializationContext) throws Exception { 87 | // no initialization needed 88 | } 89 | 90 | @Override 91 | public void close() throws Exception { 92 | if (batchProcessor != null) { 93 | batchProcessor.close(); 94 | batchProcessor = null; 95 | } 96 | 97 | if (client != null) { 98 | client.close(); 99 | client = null; 100 | } 101 | checkErrorAndRethrow(); 102 | } 103 | 104 | private void checkErrorAndRethrow() { 105 | Throwable cause = failureThrowable.get(); 106 | if (cause != null) { 107 | throw new RuntimeException("An error occurred in ClickhouseSink.", cause); 108 | } 109 | } 110 | 111 | 112 | private class BatchProcessorListener implements BatchProcessor.Listener { 113 | 114 | private static final int HTTP_OK = 200; 115 | 116 | @Override 117 | public void handleResponse(long executionId, TableRowsBuffer tableRowsBuffer, Response response) { 118 | if (response.getStatusCode() != HTTP_OK) { 119 | String errorString = response.getResponseBody(); 120 | logger.error("Failed to send data to ClickHouse, ClickHouse response = {}. ", errorString); 121 | failureThrowable.compareAndSet(null, new ClickhouseException(errorString)); 122 | } else { 123 | logger.info("Successful send data to ClickHouse, batch size = {}, target table = {}", tableRowsBuffer.bufferSize(), tableRowsBuffer.getTable()); 124 | } 125 | if (flushOnCheckpoint) { 126 | numPendingRows.getAndAdd(-tableRowsBuffer.bufferSize()); 127 | } 128 | } 129 | 130 | @Override 131 | public void handleExceptionWhenGettingResponse(long executionId, TableRowsBuffer tableRowsBuffer, Throwable failure) { 132 | logger.error("Failed to send data to ClickHouse: {}", failure.getMessage(), failure.getCause()); 133 | failureThrowable.compareAndSet(null, new ClickhouseException(failure.getMessage(), failure.getCause())); 134 | if (flushOnCheckpoint) { 135 | numPendingRows.getAndAdd(-tableRowsBuffer.bufferSize()); 136 | } 137 | } 138 | } 139 | 140 | 141 | } 142 | -------------------------------------------------------------------------------- /clickhouse-sink.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /src/main/java/tech/hongshen/clickhouse/core/BatchProcessor.java: -------------------------------------------------------------------------------- 1 | package tech.hongshen.clickhouse.core; 2 | 3 | import io.netty.handler.codec.http.HttpHeaderNames; 4 | import org.asynchttpclient.*; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import tech.hongshen.clickhouse.common.ClickHouseConfig; 8 | import tech.hongshen.clickhouse.common.ChThreadFactory; 9 | 10 | import java.io.Closeable; 11 | import java.util.concurrent.*; 12 | import java.util.concurrent.atomic.AtomicLong; 13 | 14 | /** 15 | * @author hongshen 16 | * @date 2020/12/24 17 | */ 18 | public class BatchProcessor implements Closeable { 19 | 20 | private static final Logger logger = LoggerFactory.getLogger(BatchProcessor.class); 21 | 22 | private final AsyncHttpClient client; 23 | private volatile boolean closed = false; 24 | private final String targetTable; 25 | private final int maxFlushRows; 26 | private final int flushIntervalSec; 27 | private final Listener listener; 28 | private final ClickHouseConfig config; 29 | private TableRowsBuffer tableRowsBuffer; 30 | private final ScheduledThreadPoolExecutor scheduler; 31 | private final ExecutorService callbackService; 32 | private final ScheduledFuture scheduledFuture; 33 | private final AtomicLong executionIdGen = new AtomicLong(); 34 | 35 | 36 | public BatchProcessor(AsyncHttpClient client, ClickHouseConfig config, int taskIndex, String targetTable, int maxFlushRows, Listener listener) { 37 | this.client = client; 38 | this.targetTable = targetTable; 39 | this.maxFlushRows = maxFlushRows; 40 | this.config = config; 41 | this.flushIntervalSec = config.getFlushInterval(); 42 | this.listener = listener; 43 | this.tableRowsBuffer = new TableRowsBuffer(targetTable); 44 | int cores = Runtime.getRuntime().availableProcessors(); 45 | int coreThreadsNum = Math.max(cores / 4, 2); 46 | 47 | this.callbackService = new ThreadPoolExecutor( 48 | coreThreadsNum, 49 | Integer.MAX_VALUE, 50 | 60L, 51 | TimeUnit.SECONDS, 52 | new LinkedBlockingQueue<>(), 53 | new ChThreadFactory("writer-callback", taskIndex) 54 | ); 55 | 56 | this.scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool( 57 | 1, 58 | new ChThreadFactory((targetTable != null ? "[" + targetTable + "]" : "") + "timer-flusher", taskIndex) 59 | ); 60 | this.scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); 61 | this.scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); 62 | this.scheduledFuture = this.scheduler.scheduleWithFixedDelay(new TimeFlusher(), flushIntervalSec, flushIntervalSec, TimeUnit.SECONDS); 63 | } 64 | 65 | public synchronized void add(String request) { 66 | ensureOpen(); 67 | tableRowsBuffer.add(request); 68 | executeIfNeeded(); 69 | } 70 | 71 | private void executeIfNeeded() { 72 | ensureOpen(); 73 | if (isOverTheLimit()) { 74 | execute(); 75 | } 76 | } 77 | 78 | private boolean isOverTheLimit() { 79 | return maxFlushRows != -1 && tableRowsBuffer.bufferSize() >= maxFlushRows; 80 | } 81 | 82 | 83 | class TimeFlusher implements Runnable { 84 | TimeFlusher() { 85 | } 86 | 87 | public void run() { 88 | synchronized (BatchProcessor.this) { 89 | if (!closed) { 90 | if (tableRowsBuffer.bufferSize() != 0) { 91 | execute(); 92 | } 93 | } 94 | } 95 | } 96 | } 97 | 98 | 99 | private void execute() { 100 | final TableRowsBuffer tableRowsBuffer = this.tableRowsBuffer; 101 | final long executionId = executionIdGen.incrementAndGet(); 102 | 103 | this.tableRowsBuffer = new TableRowsBuffer(targetTable); 104 | Request request = buildRequest(tableRowsBuffer); 105 | logger.info("Ready to load data to {}, size = {}", tableRowsBuffer.getTable(), tableRowsBuffer.getRows().size()); 106 | 107 | boolean afterCalled = false; 108 | try { 109 | ListenableFuture response = client.executeRequest(request); 110 | afterCalled = true; 111 | Runnable callback = responseCallback(response, executionId, tableRowsBuffer); 112 | response.addListener(callback, callbackService); 113 | } catch (Exception e) { 114 | if (!afterCalled) { 115 | listener.handleExceptionWhenGettingResponse(executionId, tableRowsBuffer, e); 116 | } 117 | } 118 | } 119 | 120 | private Runnable responseCallback(ListenableFuture whenResponse, long executionId, TableRowsBuffer tableRowsBuffer) { 121 | return () -> { 122 | try { 123 | Response response = whenResponse.get(); 124 | listener.handleResponse(executionId, tableRowsBuffer, response); 125 | } catch (Exception e) { 126 | logger.error("Error while executing callback", e); 127 | listener.handleExceptionWhenGettingResponse(executionId, tableRowsBuffer, e); 128 | } 129 | }; 130 | } 131 | 132 | private Request buildRequest(TableRowsBuffer tableRowsBuffer) { 133 | String csv = String.join(" , ", tableRowsBuffer.getRows()); 134 | String query = String.format("INSERT INTO %s VALUES %s", tableRowsBuffer.getTable(), csv); 135 | String host = config.getConnectConfig().getRandomHostUrl(); 136 | 137 | BoundRequestBuilder builder = client 138 | .preparePost(host) 139 | .setHeader(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=utf-8") 140 | .setBody(query); 141 | builder.setHeader(HttpHeaderNames.AUTHORIZATION, "Basic " + config.getConnectConfig().getCredentials()); 142 | return builder.build(); 143 | } 144 | 145 | public synchronized void flush() { 146 | ensureOpen(); 147 | if (tableRowsBuffer.bufferSize() > 0) { 148 | execute(); 149 | } 150 | } 151 | 152 | @Override 153 | public void close() { 154 | if (isOpen()) { 155 | closed = true; 156 | if (this.scheduledFuture != null) { 157 | cancel(this.scheduledFuture); 158 | this.scheduler.shutdown(); 159 | } 160 | if (tableRowsBuffer.bufferSize() > 0) { 161 | execute(); 162 | } 163 | 164 | if (this.callbackService != null) { 165 | this.callbackService.shutdown(); 166 | } 167 | } 168 | } 169 | 170 | 171 | public static boolean cancel(Future toCancel) { 172 | if (toCancel != null) { 173 | return toCancel.cancel(false); 174 | } 175 | return false; 176 | } 177 | 178 | boolean isOpen() { 179 | return !this.closed; 180 | } 181 | 182 | protected void ensureOpen() { 183 | if (this.closed) { 184 | throw new IllegalStateException("batch process already closed"); 185 | } 186 | } 187 | 188 | 189 | public interface Listener { 190 | void handleResponse(long executionId, TableRowsBuffer tableRowsBuffer, Response response); 191 | 192 | void handleExceptionWhenGettingResponse(long executionId, TableRowsBuffer tableRowsBuffer, Throwable failure); 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------