Skip to main content

clickhouse mybatis batch insert cpu raise up

· 2 min read

背景

背景

使用jdbc clickhouse,批量写入,发现cpu升高非常多,升到了90%多

排查及原因

相关环境

jdk: jdk11 clickhouse 使用的sql驱动:

               <groupId>com.clickhouse</groupId>
<artifactId>clickhouse-jdbc</artifactId>
<version>0.3.2-patch11</version>

原因: 使用mybatis plus 拼写sql,批量写入2000条 sql 用mybatis 的xml 拼写 类似:

insert into table values (row1_field1 , row1_field2 ),(row1_field1 , row1_field2) .... 这里是用mybatis 的xml foreache 2000 次

线上warning日志:

Please consider to use one and only one values expression, for example: use 'values(?)' instead of 'values(?),(?)'.

由于jdbc 的parser 比较慢,需要将perpare语句改成以下形式:

insert into table values ( ?, ? )  ## 只有一次

采用的是

// Note: "insert into table values(?,?)" is treated as "insert into mytable"
try (PreparedStatement ps = conn.prepareStatement("insert into table values(?,?)")) {
ps.setString(1, "test"); // id
ps.setObject(2, LocalDateTime.now()); // timestamp
ps.addBatch(); // append parameters to the query
...
ps.executeBatch(); // issue the composed query: insert into mytable values(...)(...)...(...)
}

结果

cpu 从80%降低到30%以内 优化前:

优化前

优化后: 优化后

相关阅读