使用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

1
2
3
4
5
6
7
8
9
10
11
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();

  

 

posted @   软件匠工  阅读(888)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示