使用spring jdbcTemplate批量insert的性能问题
最近在做一个数据搬迁的工具,从ES里把数据读出来,写到mysql,又因ES的数据有延迟,所以,还需要大量的update 动作。 使用了Spring jdbcTempalte. 因数据量比较大,导致mysql不堪重负。做了些优化,性能提升了不少。特此做个笔记。
原来的做法:
1. 使用jdbcTemplate.batchUpdate()方法。
2. sql: insert into <table> values(xxx, xxx, xxx) on duplicate key update xxx=?, xxx=?,xxx=?
更新后的做法:
1. 使用 org.springframework.jdbc.object.BatchSqlUpdate 替换jdgcTemplate.batchUpdate();
2. 用replace into 替换 on duplicate key update
DataSource dataSource = this.jdbcTemplate.getDataSource();
String sql = "insert into "+this.table+"(service,endpoint,endpoint_hash,value,total,time_bucket) values (?,?,?,?,?,?) ";
BatchSqlUpdate batchSqlUpdate = new BatchSqlUpdate(dataSource,sql);
batchSqlUpdate.setBatchSize(this.nacosConfig.getIntValue("batchSize",5000));
batchSqlUpdate.setTypes(new int[]{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.BIGINT,Types.BIGINT,Types.TIMESTAMP});
for(EndpointCpm cpm : arrayList){
batchSqlUpdate.update(cpm.getService(),cpm.getEndpoint()
,this.getEndpointHash(cpm.getEndpoint()),cpm.getValue(),cpm.getTotal()
,new Timestamp(format.parseDateTime(cpm.getTimeBucket()).getMillis()));
}
batchSqlUpdate.flush();
浙公网安备 33010602011771号