- A+
所属分类:java
近期进行数据割接,老的数据表有1700万的数据,我要把这些数据割接到新的数据库表中。由于数据量比较大,我比较机智的选择了jdbcTemplate 的batchUpdate 方法来提高插入性能。 代码如下:
private void batchInsert(Integer user_id, List<WifiDataMac> macs)
{
try
{
jdbcTemplate2.batchUpdate(
"INSERT INTO `xxx_xx_xxx_" + user_id
+ "` (`xx_id`, `xxx_id`, `xxxx_id`, `xx`, `xx_kind`, `xx`, `xx_time`) VALUES (?, ?, ?, ?, ?, ?, ?)",
new BatchPreparedStatementSetter()
{
@Override
public void setValues(PreparedStatement ps, int i)
throws SQLException
{
ps.setInt(1, macs.get(i).getUser_id());
ps.setInt(2, macs.get(i).getScene_id());
ps.setInt(3, macs.get(i).getDevice_id());
ps.setString(4, macs.get(i).getMac());
ps.setInt(5, macs.get(i).getMac_kind());
ps.setString(6, macs.get(i).getDistance());
ps.setString(7, macs.get(i).getAppear_time());
}
@Override
public int getBatchSize()
{
return macs.size();
}
});
}
catch (Exception e)
{
log.error("jdbc batchInsert error!", e);
}
}
然而割接的时候,仍然慢的令人发指,每秒大约只能插入300-500条数据,跑完这1700万,得需要10个小时左右。
查询mysql资料,发现虽然使用了addbatch
方法,mysql驱动仍然是一条一条记录的提交到数据库。如果需要批量提交,需要在设置mysql驱动链接的时候加上rewriteBatchedStatements=true
参数。
下面是我的数据库连接池配置
<!-- 数据存储数据库 -->
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/device_db_test?rewriteBatchedStatements=true" />
<property name="username" value="device_db" />
<property name="password" value="device_db@123" />
<property name="maxActive" value="64" />
<property name="minIdle" value="30" />
<property name="maxIdle" value="64" />
<property name="initialSize" value="10" />
<property name="logAbandoned" value="true" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="300" />
<property name="maxWait" value="10000" />
</bean>
<bean id="jdbcTemplate2" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource2"/>
</property>
</bean>
修改完,测试发现每秒可以插入3-5万条记录。1700万数据只需要5-10分钟。
代码写的比较low。只是割接代码,low就low点吧。也就需要运行一次而已。
- 我的微信
- 这是我的微信扫一扫
-
- 我的微信公众号
- 我的微信公众号扫一扫
-