目前有这个需求,将2百万条数据添加到数据库没有用redis,首先我是调用会员的接口
返回2百万条会员信息,一条会员信息数据大概400字节左右也就是0.4kb,全部读到
内存中,得到所有数据后逻辑操作先不考虑,想问的是有什么最快的方法将2百万条数据
插入到数据库之中。理想时间8分钟左右不知道能不能搞定?
如果只针对oracle可以采用oracle的load data命令,貌似需要先把数据保存在临时文件里,然后再加载。
如果直接在程序里插,就用foreach语句来批量插效率较高
<insert id="insertMktgFlows" parameterType="java.util.List">
INSERT INTO `mktg_flow` (
`MKTG_ID`,`MKTG_WAVE_ID`,`SERV_ACC_NBR`,`MKTG_SCRIPT`,`INS_TIME`
) VALUES
<foreach collection="list" item="item" index="index" separator="," >
(#{item.mktgId},#{item.mktgWaveId},#{item.servAccNbr},#{item.mktgScript},#{item.insTime})
</foreach>
</insert>
如果不用程序插,要先把数据按一定的格式生成到文件上,还得写个小程序用sqlldr执行load data命令来吧文件导入到数据库,这种方式生成文件要花较长时间,load data命令把数据导入到数据库很快。
public boolean insertCrossEvaluation(List members)
throws Exception {
// TODO Auto-generated method stub
int result = 1;
SqlSession batchSqlSession = null;
try {
batchSqlSession = this.getSqlSessionTemplate()
.getSqlSessionFactory()
.openSession(ExecutorType.BATCH, false);// 获取批量方式的sqlsession
int batchCount = 1000;// 每批commit的个数
int batchLastIndex = batchCount;// 每批最后一个的下标
for (int index = 0; index < members.size();) {
if (batchLastIndex >= members.size()) {
batchLastIndex = members.size();
result = result * batchSqlSession.insert("MutualEvaluationMapper.insertCrossEvaluation",members.subList(index, batchLastIndex));
batchSqlSession.commit();
System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
break;// 数据插入完毕,退出循环
} else {
result = result * batchSqlSession.insert("MutualEvaluationMapper.insertCrossEvaluation",members.subList(index, batchLastIndex));
batchSqlSession.commit();
System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
index = batchLastIndex;// 设置下一批下标
batchLastIndex = index + (batchCount - 1);
}
}
batchSqlSession.commit();
}
finally {
batchSqlSession.close();
}
return Tools.getBoolean(result);
}
总共7728条数据 insert的时间大约为10s左右
分批多批次插入!!!!