使用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(); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)